JavaScript为什么console.log (2== true) 结果为false?
console.log(1 == true); //true
console.log(2 == true); //false
console.log(4 == true); //false
console.log(!!2); //true
console.log(!!2 == true) //true
那么为什么为什么console.log (2== true) 结果为false?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
number和boolean用==比较时会把boolean转换为number再比较值,true转换为number是1,
!!2则是把2转换为boolean,非零转换boolean都是true因为Boolean类型true转化成数字1,false转化成数字0,然后进行比较的
==就是个大坑,需要使用===才靠谱。http://www.ecma-international...
2 == true
根据规范 演变成
2 == Number(true)
2 == 1 //false
所以
4 == true同理任何非零数取非均为false 如:!2 为 false 对其再取非 如: !!2 为true
另一个问题:
2==true 发生数据类型的转换,非零数会转换成false 2==true 也就变成了 false==true 结果就是 false