数据类型转换
显式转换
基础类型
js
Number(123); // 123
Number(null); // 0
Number(undefined); // NaN
String(123); // "123"
Boolean(123); // true
引用类型
number
引用类型会调用 valueOf 方法,如果 valueOf 返回的是引用类型,则调用 toString 方法,反之则返回 valueOf 的值
string
引用类型会调用 toString 方法,如果 toString 返回的是引用类型,则调用 valueOf 方法,反之则返回 toString 的值
boolean
js
Number([1]); // 1
Number([1, 2]); // NaN
Number({ a: 1 }); // NaN
String([1, 2]); // "1,2"
String({ a: 1 }); // "[object Object]"
Boolean([1, 2]); // true
Boolean({ a: 1 }); // true
隐式转换
自动转换为布尔值
- 条件判断
if
- 逻辑运算
!
自动转换为字符串
1.字符串做加法(拼接)操作时
js
console.log("1" + 1); // "11"
console.log("1" + null); // "1null"
console.log("1" + undefined); // "1undefined"
console.log("1" + true); // "1true"
console.log("1" + false); // "1false"
console.log("1" + NaN); // "1NaN"
console.log("1" + Infinity); // "1Infinity"
console.log("1" + -Infinity); // "1-Infinity"
console.log("1" + Symbol()); // "1Symbol()"
console.log("1" + BigInt(1)); // "11"
// 拼接对象 对象先调toString 再调valueOf
console.log("1" + {}); // "1[object Object]"
console.log("1" + []); // "1"
console.log("1" + [1, 2]); // "11,2"
自动转换为数字
js
console.log(1 + null); // 1
console.log(1 + undefined); // NaN
console.log(1 + true); // 2
console.log(1 + false); // 1
console.log(1 + NaN); // NaN
console.log(1 + Infinity); // Infinity
console.log(1 + -Infinity); // -Infinity
console.log(1 + Symbol()); // NaN
console.log(1 + BigInt(1)); // 2
题目
1.JavaScript 如何实现数据类型转换
转换方式有两种 显示转换和隐式转换
显式转换
- Number 先去调用 valueOf 如基础类型折返回使用 如复杂类型则调用 toString 方法
- String 先去调用 toString 结果为基础类型直接使用 复杂类型 调用 valueOf
- Boolean
隐式转换
- 自动转换为布尔值 内部使用的
Boolean
函数 - 自动转换为字符串 内部使用的
String
函数 - 自动转换为数字 内部使用的
Number
函数 JS 引擎内部使用
- 自动转换为布尔值 内部使用的