原始值 | 转换为数字 | 转换为字符串 | 转换为逻辑 |
---|---|---|---|
false | 0 | “false” | false |
true | 1 | “true” | true |
0 | 0 | “0” | false |
1 | 1 | “1” | true |
“0” | 0 | “0” | true |
“000” | 0 | “000” | true |
“1” | 1 | “1” | true |
NaN | NaN | “NaN” | false |
Infinity | Infinity | “Infinity” | true |
-Infinity | -Infinity | “-Infinity” | true |
“” | 0 | “” | false |
“20” | 20 | “20” | true |
“twenty” | NaN | “twenty” | true |
[ ] | 0 | “” | true |
[20] | 20 | “20” | true |
[10,20] | NaN | “10,20” | true |
[“twenty”] | NaN | “twenty” | true |
[“ten”,”twenty”] | NaN | “ten,twenty” | true |
function(){} | NaN | “function(){}” | true |
{ } | NaN | “[object Object]” | true |
null | 0 | “null” | false |
undefined | NaN | “undefined” | false |
下列结果是true:(== 操作符永远不会将操作数转换为boolean)
- null == undefined // 特殊
- undefined == undefined
- null == null
- 0 == “0” // 两个操作数先转换为数字再比较
- 0 == “” // 两个操作数先转换为数字再比较
- 0 == false // 两个操作数先转换为数字再比较
- “0” == false // 两个操作数先转换为数字再比较
下列结果是false:(不会发生类型转换)
- undefined == false
- undefined == true
- undefined == 0
- undefined == “0”
- undefined == “”
- null == false
- null == true
- null == 0
- null == “0”
- null == “”
字符串隐式转换数字时支持前后有空格,但其他索引位置的字符必须为数字,否则结果为NaN。
parseFloat,parseInt 字符串开头有数字就可以有数值结果,转到不能转换的索引位置时停止,输出结果为前面已转好的数字(能转几个算几个),开头如果非数字直接NaN。
数组转换数值时,默认调用toString()方法先转换为字符串,再由字符串转换为数值。
toString(基数)可以输出指定基数的数值(用于十进制转其他),parseFloat,parseInt可以按指定基数解析字符串返回十进制数值。(基本上表达式返回的数字都是十进制数值,除非用toString指定其他基数)