2017-09-20 39 views
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

三個有趣的記載:

  1. why null==undefined is true in javascript
  2. Why does (true > null) always return true in JavaScript?
  3. What exactly is Type Coercion in Javascript?
+5

了''==操作符的語義是不與用於布爾值的任意值的評估規則相同。 – Pointy

+0

在這裏閱讀關於強制類型,你會更好地理解它:https://stackoverflow.com/questions/19915688/what-exactly-is-type-coercion-in-javascript – pegla

+3

具體來說,'=='(或「鬆散等於「)運算符[比較兩個值的均等性_after_將這兩個值轉換爲常見類型](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Equality_comparisons_and_sameness#Loose_equality_using) – Hamms

回答

2

==運算符有其自己的語義。你正在比較沒有被定義爲相同的行爲。

如果你想看到正常的「truthy/falsy」的評價工作,你應該使用的value == falsevalue == true!value!!value代替:

if (!null) console.log("hi"); 
if (!NaN) console.log("hi"); 
相關問題