search
HomeWeb Front-endJS TutorialJavaScript Topic 7: Type Conversion
JavaScript Topic 7: Type ConversionMar 10, 2021 am 10:32 AM
javascripttype conversion

JavaScript Topic 7: Type Conversion

Contents

  • Preface
  • 1. What is type conversion?
  • 2. Basic rules for primitive value conversion
  • 3. Convert objects to strings and numbers
  • 4. Common type conversion operators
  • 5. Common type conversion operations
  • are written at the end

(free learning recommendation: javascript video tutorial

##Preface

Before understanding type conversion, if you still have doubts about the basic types of Js, you may wish to read Take a look at this article about basic data types in JavaScript~

Type conversions are often criticized, but in fact they are very useful in many cases. Some forced type conversions can clearly tell us where type conversions have occurred. Helps improve code readability and maintainability. But some of them happen in places we can't see, so today we will discuss common type conversion operations and operations~

1. What is type conversion?

We all know that the type of a variable is determined by the type of value it stores, so converting a value from one type to another is usually called type-casting, and It can also be divided into two categories according to certain characteristics

    Explicit type conversion
  • Implicit type conversion.

Explicit type conversion

Explicit type conversion mainly refers to converting corresponding strings, numbers, Boolean through String, Number, Boolean and other construction methods Value

const str = String(1);const num = Number("123.3"); //number:123.3
This is an explicit case - the type conversion action is initiated by us.

1.2 Implicit type conversion
const newStr1 = 1 + "str"; // '1str'const newStr2 = "hello" + [89, 150.156, "mike"]; // 'hello89,150.156,mike'
If students working in C, Java and other strongly typed languages ​​write similar combinations, they should report an error, but not in Js.

Since implicit type conversion will always exist, we must accept it and understand its advantages and disadvantages!

JavaScript Topic 7: Type Conversion

2. Basic rules of conversion

The conversion between some data types will go through "multiple processes". We Try to introduce the few "processes" first~

2.1 Converting original value to string
We use the String function to convert the type into a string type. If the

String function does not pass Parameters, return an empty string. If there are parameters, call ToString(value), and ToString also gives a corresponding result table. The table is as follows:

Rules:

Parameter typeReturnUndefined"undefined"Null"null"BooleanIf the parameter is true, return "true". The parameter is false, and "false" is returned NumberThere are many results, such as NaN and InfinityStringReturn a value equal to

Example:

console.log(String()); // 空字符串console.log(String(undefined)); // undefinedconsole.log(String(null)); // nullconsole.log(String(false)); // falseconsole.log(String(true)); // true// Numberconsole.log(String(0)); // 0console.log(String(-0)); // 0console.log(String(NaN)); // NaNconsole.log(String(Infinity)); // Infinityconsole.log(String(-Infinity)); // -Infinityconsole.log(String(1)); // 1
2.2 Convert original value to number
Sometimes we need to use non-numeric values ​​as numbers, such as mathematical operations. For this reason, the ES5 specification defines the abstract operation

ToNumber in Section 9.3. Similar to ToString, it also has certain conversion rules:

Parameter typeReturntrue1false0undefinedNaNnull0StringReturns an equal value, but returns NaN if processing fails
console.log(Number(true)); // 1console.log(Number(false)); // 0console.log(Number(undefined)); // NaNconsole.log(Number("余光")); // NaNconsole.log(Number("1")); // 1
2.3 原始值转布尔

我们使用 Boolean 函数将类型转换成布尔类型,在 JavaScript 中,只有 6 种 值可以被转换成false,其他都会被转换成true

console.log(Boolean()); // falseconsole.log(Boolean(false)); // falseconsole.log(Boolean(undefined)); // falseconsole.log(Boolean(null)); // falseconsole.log(Boolean(+0)); // falseconsole.log(Boolean(-0)); // falseconsole.log(Boolean(NaN)); // falseconsole.log(Boolean("")); // false
2.4 原始值转对象

原始值到对象的转换非常简单,原始值通过调用 String()、Number() 或者 Boolean() 构造函数,转换为它们各自的包装对象

nullundefined 属于例外,当将它们用在期望是一个对象的地方都会造成一个类型错误 (TypeError) 异常,而不会执行正常的转换。

var a = 1;console.log(typeof a); // numbervar b = new Number(a);console.log(typeof b); // object

三、对象转字符串和数字

3.0 对象转布尔值

3.0 这一小节是我认为值得一提,但篇幅较少的一点:

对象到布尔值的转换非常简单:所有对象(包括数组和函数)都转换为 true。对于包装对象也是这样,举个例子:

console.log(Boolean(new Boolean(false))); // true
3.1 对象的 toString 和 valueOf

这是一个不太常见的操作,或者说现象,但我们也不能忽略它。

  1. 对象=>字符串
  2. 对象=>数字

转换都是通过调用待转换对象的一个方法来完成的,在 Js 中,一般待转换对象拥有两个方法:

  1. toString
  2. valueOf

toString

所有的对象除了nullundefined之外的任何值都具有toString方法,通常情况下,它和使用String方法返回的结果一致。

在JavaSciprt 专题之类型检测中我们提到过Object.prototype.toString 方法会根据这个对象的[[class]]内部属性,返回由 "[object " 和 class 和 “]” 三个部分组成的字符串。举个例子:

const obj = { name: "余光" };obj.toString(); // "[object Object]"obj.toString === Object.prototype.toString; // true

我们已经验证了 => 对象调用 toString 方法是调用其构造函数原型上的方法

其他数据类型的 toString 方法也都有自己的特点:

  • 数组:将每个数组元素转换成一个字符串,并在元素之间添加逗号后合并成结果字符串。
  • 函数:返回源代码字符串。
[1, 2, 3, 4].toString(); // "1,2,3,4"[].toString(); // ""function func() {
  console.log();}func.toString(); // "function func () { console.log() }"

valueOf

valueOf 方法返回这个对象本身,数组、函数、正则简单的继承了这个默认方法,也会返回对象本身。日期是一个例外,它会返回它的一个内容表示: 1970 年 1 月 1 日以来的毫秒数。

var date = new Date(2017, 4, 21);console.log(date.valueOf()); // 1495296000000
3.2 对象转字符串和数字的基本规则

在我们知道了 toString()和 valueOf()这两个方法后,来看看转换的规则,即什么时候用:ES5 规范 9.8

参数类型 结果
Object 1. primValue = ToPrimitive(input, String)
2. 返回 ToString(primValue)

所谓的 ToPrimitive 方法,其实就是输入一个值,然后返回一个一定是基本类型的值。

我们总结一下,当我们用 String 方法转化一个值的时候:

  1. 基本类型:参照 “原始值转字符” 的对应表
  2. 引用类型:调用一个ToPrimitive方法,将其转为基本类型,然后再参照 “原始值转字符” 的对应表进行转换。

其实,从对象到数字的转换也是一样:

参数类型 结果
Object 1. primValue = ToPrimitive(input, Number)
2. 返回 ToNumber(primValue)

注意:转字符和数字的时候处理略有不同~

3.3 ToPrimitive

那接下来就要看看 ToPrimitive 了,ES5 规范 9.1

这个返回原始值的方法接受一个输入参数 和一个可选的参数来表示转换类型:

  1. input,表示要处理的输入值
    • 如果传入的 input 是 Undefined、Null、Boolean、Number、String 类型,直接返回该值。
  2. PreferredType,非必填,表示希望转换成的类型,有两个值可以选,Number 或者 String。
    • 当不传入 PreferredType 时,如果 input 是日期类型,相当于传入 String,否则,都相当于传入 Number。
如果是 ToPrimitive(obj, Number),处理步骤如下:
  • 如果 obj 为 基本类型,直接返回
  • 否则,调用 valueOf 方法,如果返回一个原始值,则 JavaScript 将其返回。
  • 否则,调用 toString 方法,如果返回一个原始值,则 JavaScript 将其返回。
  • 否则,JavaScript 抛出一个类型错误异常。
如果是 ToPrimitive(obj, String),处理步骤如下:
  • 如果 obj 为 基本类型,直接返回
  • 否则,调用 toString 方法,如果返回一个原始值,则 JavaScript 将其返回。
  • 否则,调用 valueOf 方法,如果返回一个原始值,则 JavaScript 将其返回。
  • 否则,JavaScript 抛出一个类型错误异常。

所以总结下,对象转字符串(就是 Number() 函数)可以概括为:

举个例子:

console.log(Number({})); // NaNconsole.log(Number({ a: 1 })); // NaNconsole.log(Number([])); // 0console.log(Number([0])); // 0console.log(Number([1, 2, 3])); // NaNconsole.log(
  Number(function() {
    var a = 1;
  })); // NaNconsole.log(Number(/\d+/g)); // NaNconsole.log(Number(new Date(2010, 0, 1))); // 1262275200000console.log(Number(new Error("a"))); // NaN

注意:

  • 转换对象时,你会发现它变成了 NaN,所以

  • 在这个例子中,[][0]都返回了 0

    • 当我们 Number([]) 的时候,先调用 []valueOf 方法,此时返回 []
    • 因为返回了一个对象,所以又调用了 toString 方法;
    • 此时返回一个空字符串,接下来调用 ToNumber 这个规范上的方法;
    • 等价于 Number([].valueOf().toString()),结果为 0;
  • [1, 2, 3] 却返回了一个 NaN:

    • 当我们 Number([]) 的时候,先调用 [1,2,3]valueOf 方法,此时返回 [1,2,3];
    • 因为返回了一个对象,所以又调用了 toString 方法;
    • 此时为1,2,3,接下来调用 ToNumber 这个规范上的方法;
    • 等价于 Number([1,2,3].valueOf().toString()),结果为 NaN;

JavaScript Topic 7: Type Conversion

四、涉及到类型转换的运算符

读到这里我们对类型转换有了一定的概念,现在我们再来看看在运算中常见的类型转换问题。

4.1 一元操作符 +

+a 运算符显式地将后面的变量 a 保存的数据转换为数字,不是字符串拼接。
查看 ES5 规范 11.4.6,会调用 ToNumber 处理该值,相当于 Number(‘1’),最终结果返回数字 1。

const a = "1.1";const b = 5 + +a;console.log(b); // 6.6

上面的代码应该是我们经常用到的,当我们知道一个字段是字符串但希望它是数字时,一般会这么做~

我们一起验证下下面这些类型

console.log(+[]); // 0console.log(+["1"]); // 1console.log(+["1", "2", "3"]); // NaNconsole.log(+{}); // NaN

既然是调用 ToNumber 方法我们在之前的小节中提到过

  • 如果 obj 为基本类型,直接返回
  • 否则,调用 valueOf 方法,如果返回一个原始值,则 JavaScript 将其返回。
  • 否则,调用 toString 方法,如果返回一个原始值,则 JavaScript 将其返回。
  • 否则,JavaScript 抛出一个类型错误异常。
  • +[] 为例,[] 调用 valueOf 方法,返回一个空数组,因为不是原始值,调用 toString 方法,返回 ""
  • 得到返回值后,然后再调用 ToNumber 方法,"" 对应的返回值是 0,所以最终返回 0。
4.2 一元操作符 !

一元运算符!显式地将值强制类型转换为布尔值。但是它同时还将真值反转为假值(或者将假值反转为真值)。

const a = 1;const b = "str";const c = [1, 2, 3];console.log(!a); // falseconsole.log(!b); // falseconsole.log(!c); // falseconsole.log(!0); // trueconsole.log(!""); // trueconsole.log(![]); //falseconsole.log(![]); //falseconsole.log(!undefined); // trueconsole.log(!null); // true

同样的 !! 会讲其他类型转成对应的 bool 值

!和 + 运算符是我们最常用的两种显式类型转换运算符,之后我们再看看那些不经意间就被转换类型的操作~

五、常见的类型转换操作

5.1 字符串和数字之间
const num = 1;const str = "200";console.log(num + str); // '1200'

这段代码大家应该都知道结果,但是其中的原理是否和大家想的一样呢?

const arr1 = [1, 2];const arr2 = [3, 4];console.log(arr1 + arr2); // 1,23,4

两个数组的结果为什么也是个字符串?

原因

ES5 规范 11.6.1 中提到,如果某个操作数是字符串或者能通过以下步骤转换为字符串,+将进行拼接操作

如果其中的一个操作数是引用类型,则首先对其进行ToPrimitive操作(第三小节有提)

总结

简单来说就是,如果+的其中一个操作数是字符串(或者通过以上步骤可以得到字符串),则执行字符串拼接;否则执行数字加法。

5.2 被转换成布尔值的操作

现在我们来看看到布尔值的隐式强制类型转换,它最为常见也最容易搞错。相对布尔值,数字和字符串操作中的隐式强制类型转换还算比较明显。

下面的情况会发生布尔值隐式强制类型转换。

  • if (…)语句
    • 括号内的条件为true时执行操作;
  • for ( let i = 0; i
  • 语句中的条件判断表达式即 i true
  • while (…)和 do…while(…)
    • 循环中的条件判断表达式为true;
  • 三目运算 ? :
  • 逻辑运算符 ||(逻辑或)和 &&(逻辑与)左边的操作数;
  • 5.3 == 和 ===

    谈到类型转换,一定绕不开 =====

    ==用于比较两个值是否相等,当要比较的两个值类型不一样的时候,就会发生类型的转换。

    在ES5 规范 11.9.5 中简述了它的规则:

    当执行 x == y 时:

    • 如果 x 与 y 是同一类型:
      • x 是 Undefined,返回 true
      • x 是 Null,返回 true
      • x 是数字:
        • x 是 NaN,返回 false
        • y 是 NaN,返回 false
        • x 与 y 相等,返回 true
        • x 是+0,y 是-0,返回 true
        • x 是-0,y 是+0,返回 true
      • x 是字符串,完全相等返回 true,否则返回 false
      • x 是布尔值,x 和 y 都是 true 或者 false,返回 true,否则返回 false
      • x 和 y 指向同一个对象,返回 true,否则返回 false
    • x 是 null 并且 y 是 undefined,返回 true
    • x 是 undefined 并且 y 是 null,返回 true
    • x 是数字,y 是字符串,判断 x == ToNumber(y)
    • x 是字符串,y 是数字,判断 ToNumber(x) == y
    • x 是布尔值,判断 ToNumber(x) == y
    • y 是布尔值,判断 x ==ToNumber(y)
    • x 不是字符串或者数字,y 是对象,判断 x == ToPrimitive(y)
    • x 是对象,y 不是字符串或者数字,判断 ToPrimitive(x) == yJavaScript Topic 7: Type Conversion

    相关免费学习推荐:javascript(视频)

    The above is the detailed content of JavaScript Topic 7: Type Conversion. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
    es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

    去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

    JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

    本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

    原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

    怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

    JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

    本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

    JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

    本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

    javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

    方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

    整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

    本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

    foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

    foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    Repo: How To Revive Teammates
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    Hello Kitty Island Adventure: How To Get Giant Seeds
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

    MantisBT

    MantisBT

    Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    ZendStudio 13.5.1 Mac

    ZendStudio 13.5.1 Mac

    Powerful PHP integrated development environment