1、首先要知道 JavaScript
中有 6 中基本类型:
- boolean
- number
- string
- null
- undefined
- symbol – ES6 中新添加的基本类型
而这些基本数据类型之间的转化,也就只有下面三种:转为布尔值
、转为数值
、转为字符串
。
详细的转换规则参见下图:
上图中包含了所有转换规则,这里总结几点需要注意的地方:
NaN
是number
类型的数据,所以number
转其他类型时不要漏掉它。- 对象转字符串,结果为:
[object Object]
- 数组转数字的规则:空数组、只有一个数字元素的数组转为数字,其余情况均为
NaN
undefined
和null
转数字,分别为:NaN
和0
- 转为
Boolean
时,除了undefined
,null
,false
,NaN
,0
,-0
转为false
,其他的都转为true
,包括所有对象。
2、对于 对象 转换为 基本类型 时,其内部的原理如下:
- 如果已经是基本类型,直接返回
- 调用内置的 valueOf、toString 方法,如果转换为基本类型,则返回转换的值
- 如果没有转换为基本类型,则会抛出错误
3、类型转换的一些小技巧
- 数据前置
+
号,转换为number
类型 - 数据与
0
相减,转换为number
类型 - 数据前置
!!
号,转换为Boolean
类型
例如:
console.log(+'10'); // => 10
console.log(+'a'); // => NaN
console.log('10' - 0); // => 10
console.log('a' - 0); // => NaN
console.log(!!'hello world'); // true
console.log(!!null); // false
以上 ?
还没有人抢沙发呢~