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