JS类型转换基本可以分为:原始类型转换成其它的原始类型,如Number类型转换成Boolean类型;对象转换成原始类型
一、原始类型相互转换
JS中类型转换只有三种情况
a.转换成bool值
b.转换成数字
c.转换成字符串
1. Number -> Boolean
除了0、-0、NaN,其它都为true
console.log(!!1) // true
console.log(!!0) // false
console.log(!!-1) // true
console.log(!!-0) // false
console.log(!!+1) // true
console.log(!!+0) // false
console.log(!!Infinity) // true
console.log(!!-Infinity) // true
console.log(!!NaN) // false
2. Number -> String
这个比较容易,类似5 => ‘5’这种形式
3. String -> Boolean
除了空串以外,其它的都为true
console.log(!!'') // false
console.log(!!' ') // true
console.log(!!'hello') // true
console.log(!!'false') // true
console.log(!!'0') // true
4.String -> number
如果字符串为有效的数字的话,就转换成数字,如果不是有效数字就会被转换成NaN,有效数字包括八进制数字
console.log(+'0') // 0
console.log(+'0x12') // 18 八进制数字
console.log(+'a') // NaN
console.log(+'12.3') // 12.3
console.log(+'100010') // 10010
console.log(+'-0') // -0
console.log(+'010') // 10
5. undefined null -> Boolean
undefined和null转成bool值,都为false
6. null 转换成数字
null 转换成数字 值为0
7.数组转换成数字
空数组为0,存在一个元素且该元素为数字或者是有效的字符串数字,则转换成数字,其它情况为NaN
console.log(+[]) // 0
console.log(+[1]) // 1
console.log(+['1']) // 1
console.log(+[1,2]) // NaN
console.log(+[0x12]) // 18
console.log(+['0x12']) // 18
console.log(+['a']) // NaN
8. 引用类型 -> Boolean
引用类型转换成bool值都为true
9. 数组 -> 字符串
类似[1,2] -> '1, 2'
10.引用类型 -> Number
除了数组之外都是NaN
二 、对象转原始类型
对象在转换成原始类型的时候,一般会调用内置的[[toPrimitive]]函数
如果已经是原始对象了那么就不需要转换
如果需要转换成字符串就调用x.toString(),转换成基础类型的话,就返回调用的值,不是字符串类型就先调用valueof,如果不是基本类型就再调用toString
我们可以通过Symbol.toPrimitive来重写方法
let a = {
valueOf() {
return 1
},
toString() {
return 'a'
},
[Symbol.toPrimitive] () {
return 'Symbol'
}
}
三、四则运算符
1. 加号
a. 运算符一方如果是字符串,那么就会把另一方也抓换成字符串
b.如果一方不是字符串或者数字,那么就会把它转换成字符串或者数字
console.log(1 + '1') // '11'
console.log('a' + '0') // 'a0'
console.log(true + false) // 1
console.log(1 + [1,2,3]) // '11,2,3'
console.log(1 + [1]) // '11'
2. 其它运算符
一方是数字,就会把另一方也转换成数字
四、比较运算符 a == b
1. a 的 type 和 b 的 type相同
值相同返回true否则返回false,结果跟a === b一样
2. a 或者 b 有一方为null,另一方为undefined
结果返回true
3. a 或者 b 由乙方为number, 另一方为string
将string转换成数字进行比较
4. a 或者 b为bool类型
将bool类型转换成数字类型,在进行比较
5.如果a 或者 b其中有一个为引用类型
调用引用类型的toPrimitive方法转换成原始类型