强制转换
Number、String和Boolean三个函数
其他的数据类型转换为String
- toString()方法
- String()函数
其他的数据类型转换为Number
- parseInt() & parseFloat()
- Number()
两者的区别:Number更严格,parseInt可以自动将里面的字符串过滤。
其他的数据类型转换为Boolean
只有空字符串("")、null、undefined、+0、-0 和 NaN 转为布尔型是 false,其他的都是 true,空数组、空对象转换为布尔类型也是 true,甚至连false对应的布尔对象new Boolean(false)也是true
Boolean(undefined) // false
自动转换
自动转换为布尔值
if ('abc') {
console.log('hello')
} // "hello"
自动转换为数值
算数运算符(+ - * /)跟非Number类型的值进行运算时,会将这些值转换为Number,然后在运算,除了字符串的加法运算
true + 1 // 2
2 + null // 2
undefined + 1 // NaN
2 + NaN // NaN 任何值和NaN做运算都得NaN
'5' - '2' // 3
'5' * '2' // 10
true - 1 // 0
'1' - 1 // 0
'5' * [] // 0
false / '5' // 0
'abc' - 1 // NaN
自动转换为字符串
字符串的自动转换,主要发生在字符串的加法运算时。当一个值为字符串,另一个值为非字符串,则后者转为字符串。
'5' + 1 // '51'
'5' + true // "5true"
'5' + false // "5false"
'5' + {} // "5[object Object]"
'5' + [] // "5"
'5' + function (){} // "5function (){}"
'5' + undefined // "5undefined"
'5' + null // "5null"