2013-01-04 41 views
2

可能重複:
Why `null >= 0 && null <= 0` but not `null == 0`?JavaScript的平等返回false

所有的假設是正確的:

alert("null==undefined: " + (null == undefined)) 
alert("null==0:   " + (null == 0))  // why false?? 
alert("false=='':  " + (false == '')) 
alert("true==1:   " + (true == 1)) 
alert("true=='1':  " + (true == '1')) 
alert("'1'==1:   " + ('1' == 1)) 

所有的假設是錯誤的:

alert("null===undefined: " + (null === undefined)) 
alert("null===0:   " + (null === 0)) 
alert("false==='':  " + (false === '')) 
alert("true===1:   " + (true === 1)) 
alert("true==='1':  " + (true === '1')) 
alert("'1'===1:   " + ('1' === 1)) 

爲什麼(null == 0)是假的

我使用最後一個chrome來測試它。

+2

你爲什麼期望它是「真」? – Bergi

+1

http://stackoverflow.com/questions/2910495/why-null-0-null-0-but-not-null-0 –

+0

因爲'null'和'0'不等價。 – Shmiddty

回答

3

null類型與number類型沒有真正的可比性,所以comparison algorithm返回false。從規範(省略關聯案例):

  1. 如果類型相同,請使用類型特定的比較。
  2. null == undefinedtrue
  3. 數字和字符串作爲數字進行比較,則該字符串被轉換
  4. 如果布爾相比,它被轉換爲數字,並再次進行比較
  5. 如果數字或字符串與對象相比,該對象被轉換爲原語並再次進行比較 - 並且不,Type(null)Null,而不是對象(如在typeof operator中)。
  6. 對於其他所有,return false
+0

準確地說,它是[算法的第10步](http://es5.github.com/#x11.9.3)。看起來'null'只能與本身和未定義相比。 – bfavaretto

+0

@bfavaretto'null'是一個對象,所以它應該是步驟8或9,而不是10. – kojiro

+0

但是null是類型對象。這不清楚。 –