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
大坑!@#¥%……&已吐*