1
我被从名单上here检查所有falsey值的平等测试JavaScript中的所有falsy值不等于假不打印hi
:为什么当平等
if(null == false) console.log('hi');
if(undefined == false) console.log('hi');
if(NaN == false) console.log('hi');
所有其他falsey值最终打印文本hi
,如下图所示:
if('' == false) console.log('hi');
if(0x0 == false) console.log('hi');
if(false == false) console.log('hi');
if(0.0 == false) console.log('hi');
if(0 == false) console.log('hi');
任何人都可以帮我理解这种行为背后的原因吗?
更新为未来的读者:
如果你想环绕falsy价值观和平等经营的怪事你的头在JavaScript三个有趣的记载:
- why null==undefined is true in javascript
- Why does (true > null) always return true in JavaScript?
- What exactly is Type Coercion in Javascript?
了''==操作符的语义是不与用于布尔值的任意值的评估规则相同。 – Pointy
在这里阅读关于强制类型,你会更好地理解它:https://stackoverflow.com/questions/19915688/what-exactly-is-type-coercion-in-javascript – pegla
具体来说,'=='(或“松散等于“)运算符[比较两个值的均等性_after_将这两个值转换为常见类型](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Equality_comparisons_and_sameness#Loose_equality_using) – Hamms