隐式和显式转换有什么区别?
隐式强制转换是一种将值转换为另一种类型的方法,这个过程是自动完成的,无需我们手动操作。
假设我们下面有一个例子。
console.log(1 + '6'); // 16 console.log(false + true); // 1 console.log(6 * '2'); // 12
第一个console.log
语句结果为16
。在其他语言中,这会抛出编译时错误,但在 JS 中,1
被转换成字符串,然后与+运
算符连接。我们没有做任何事情,它是由 JS 自动完成。
第二个console.log
语句结果为1
,JS 将false
转换为boolean
值为 0
,,true
为1
,因此结果为1
。
第三个console.log
语句结果12
,它将'2'
转换为一个数字,然后乘以6 * 2
,结果是12。
而显式强制是将值转换为另一种类型的方法,我们需要手动转换。
console.log(1 + parseInt('6'));
在本例中,我们使用parseInt
函数将'6'
转换为number
,然后使用+
运算符将1
和6
相加。