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 Valueconst str = String(1);const num = Number("123.3"); //number:123.3This 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!
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 stringWe use the String function to convert the type into a string type. If theString 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:
Return | |
---|---|
"undefined" | |
"null" | |
If the parameter is true, return "true". The parameter is false, and "false" is returned | |
There are many results, such as NaN and Infinity | |
Return 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)); // 12.2 Convert original value to numberSometimes 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:
Return | |
---|---|
1 | |
0 | |
NaN | |
0 | |
Returns an equal value, but returns NaN if processing fails |
参数类型 | 结果 |
---|---|
Object | 1. primValue = ToPrimitive(input, String) 2. 返回 ToString(primValue) |
所谓的 ToPrimitive 方法,其实就是输入一个值,然后返回一个一定是基本类型的值。
我们总结一下,当我们用 String 方法转化一个值的时候:
- 基本类型:参照 “原始值转字符” 的对应表
- 引用类型:调用一个
ToPrimitive
方法,将其转为基本类型,然后再参照 “原始值转字符” 的对应表进行转换。
其实,从对象到数字的转换也是一样:
参数类型 | 结果 |
---|---|
Object | 1. primValue = ToPrimitive(input, Number) 2. 返回 ToNumber(primValue) |
注意:转字符和数字的时候处理略有不同~
3.3 ToPrimitive
那接下来就要看看 ToPrimitive 了,ES5 规范 9.1
这个返回原始值的方法接受一个输入参数 和一个可选的参数来表示转换类型:
- input,表示要处理的输入值
- 如果传入的 input 是 Undefined、Null、Boolean、Number、String 类型,直接返回该值。
- 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;
- 当我们
四、涉及到类型转换的运算符
读到这里我们对类型转换有了一定的概念,现在我们再来看看在运算中常见的类型转换问题。
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
- 循环中的条件判断表达式为
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) == y
相关免费学习推荐: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!

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

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

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

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

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

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

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

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

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
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 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
Powerful PHP integrated development environment
