- 强制转换
Number()、String()与Boolean()三个强制转换函数,所对应的就是在ECMAScript标准中的ToNumber、ToString、ToBoolean三个内部运算转换的对照表。
通过ToNumber()把值转换成Number:
| 参数 | 结果 |
| — | — |
| undefined | NaN |
| null | +0 |
| boolean | true被转换为1,false转换为+0 |
| number | 无需转换 |
| string | 由字符串解析为数字。例如,”324″被转换为324 |
通过ToString()把值转化成字符串:
| 参数 | 结果 |
| — | — |
| undefined | “undefined” |
| null | “null” |
| boolean | “true” 或者 “false” |
| number | 数字作为字符串。比如,”1.765″ |
| string | 无需转换 |
六、从实例中理解
- 运算元其一为字符串(String)
/**
- 运算元其一为字符串(String)
*/
console.log(‘12’+1); // 121
console.log(‘abc’+‘def’); // abcdef
console.log(‘1’+true); //1true
console.log(‘1’+undefined); //1undefined
console.log(‘1’+null); //1nul