共计 1695 个字符,预计需要花费 5 分钟才能阅读完成。
JS 数据类型转换小计
数据类型
- 最新的 ECMAScript 标准定义了 7 种 数据类型
原始类型
- Boolean
- Null
- Undefined
- Number
- String
- Symbol
对象
7.Object
显式类型转换
- Number 函数
原始类型转换
数值:转换后还是原来的值
console.log(Number(123)) //123
字符串:如果可以被解析为数值,则转换为相应的数值,否则得到 NaN. 空字符串转为 0
console.log(Number('123')) //123
console.log(Number('123abc')) //NaN
console.log(Number('')) //0
布尔值:true 转换为 1,false 转换为 0
console.log(Number(true)) //1
console.log(Number(false)) //0
undefined:转换为 NaN
console.log(Number(undefined)) //NaN
null:转换为 0
console.log(Number(null)) //0
对象类型转换
- 先调用对象自身的
valueOf
方法,如果该方法返回原始类型的值(数值,字符串和布尔),则直接对该值使用Number
方法,不再进行后续步骤。 - 如果
valueOf
方法返回复合类型的值,再调用对象自身的toString
方法,如果toString
方法返回原始类型的值,则对该值使用Number
方法,不再进行后续步骤。 - 如果
toString
方法返回的是复合类型的值,则报错。console.log(Number({a:1})) //NaN
原理流程:
a.valueOf() //{a:1}
a.toString() //"[object Object\]"
Number("[object Object]") //NaN
-
String 函数
原始类型转换
数值:转为相应的字符串
字符串:转换后还是原来的值
布尔值:true 转为 ’true’,false 转为 ’false’
undefinde:转为 ’undefined’
null:转为 ’null’
对象类型转换
- 先调用
toString
方法,如果toString
方法返回的是原始类型的数值,则对该值使用 string 方法,不再进行以下步骤。 - 如果
toString
方法返回的是复合类型的值,再调用valueOf
方法,如果valueOf
方法返回的是原始类型的值,则对该值使用String
方法,不再进行以下步骤。 - 如果
valueOf
方法返回的是复合类型的值,则报错。
- Boolean 函数
原始类型转换
undefined:转为 false
null:转为 false
0:转为 false
NaN:转为 false
”(空字符串):转为 false
以上统统都转为 false, 其它转为 true
隐式类型转换
在 js 中,当运算符在运算时,如果两边数据不统一,CPU 就无法计算,这时我们编译器会自动将运算符两边的数据做一个数据类型转换,转成一样的数据类型再计算. 这种无需程序员手动转换,而由编译器自动转换的方式就称为隐式转换
- typeof
typeof underfined = 'ndefined'
typeof null = 'object'
typeof Boolean = 'function'
typeof Number = 'function'
- 常见小坑
此类问题中:+ 分为两种情况
字符串连接符:+ 号两边有一边是字符串,会把其它数据类型调用 String()方法转换成字符串然后拼接。
算术运算符:+ 号两边都是数字,会把其它数据调用 Number()方法转换成数字然后做加法运算
console.log(1 + true); // 算书运算符:1 + Number(true) = 1 + 1 = 2
console.log(1 + 'true'); // 字符串连接符:String(1) + 'true' = '1' + 'true' = '1true'
console.log(1 + undefined)// 算书运算符:1 + Number(undefined) = 1 + 0 = 1
console.log(1 + null)// 算书运算符:1 + Number(null) = 1 + 0 = 1
- 大坑 &%……&¥&%……(&))已吐。。。。。