JS数据类型转换小计
原始类型程序员
对象函数
7.Objectcode
原始类型转换对象
数值:转换后仍是原来的值ip
console.log(Number(123)) //123
字符串
字符串:若是能够被解析为数值,则转换为相应的数值,不然获得NaN.空字符串转为0编译器
console.log(Number('123')) //123
string
console.log(Number('123abc')) //NaN
io
console.log(Number('')) //0
console
布尔值: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
原始类型转换
数值:转为相应的字符串
字符串:转换后仍是原来的值
布尔值:true转为'true',false转为'false'
undefinde:转为'undefined'
null:转为'null'
对象类型转换
toString
方法,若是toString
方法返回的是原始类型的数值,则对该值使用string方法,再也不进行如下步骤。toString
方法返回的是复合类型的值,再调用valueOf
方法,若是valueOf
方法返回的是原始类型的值,则对该值使用String
方法,再也不进行如下步骤。valueOf
方法返回的是复合类型的值,则报错。原始类型转换
undefined:转为false
null:转为false
0:转为false
NaN:转为false
''(空字符串):转为false
以上通通都转为false,其它转为true
在js中,当运算符在运算时,若是两边数据不统一,CPU就没法计算,这时咱们编译器会自动将运算符两边的数据作一个数据类型转换,转成同样的数据类型再计算.这种无需程序员手动转换,而由编译器自动转换的方式就称为隐式转换
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