类型转换只有这四种,例如如果要对象转数字,那么就需要先把对象转成原始类型,再从原始类型转到数字。
空数组转原始类型是一个空字符串。空对象转原始类型是'[object Object]'。
let a = {}
console.log(+a);// NaN
//等价于 a->原始 然后原始->数字。a->原始结果是'[object Object]'。'[object Object]'转数字是NaN
const b = a.valueOf();
console.log(b);//{}
console.log(b.toString());//'[object Object]'
console.log(Number(b.toString()));//NaNlet d = {valueOf() {return 1;}
}
console.log(+d);// 1
console.log(d.valueOf());//1
console.log(Number(d));//1let e = {valueOf() {return {};},toString() {return {};}
}
console.log(e.valueOf());//{}
console.log(e.toString());//{}
console.log(Number(e));//TypeError: Cannot convert object to primitive value