2015-12-08 32 views
1

看起來像null應該等於null。那麼,爲什麼UnderscoreJS _.every for nulls

_.every([null], _.identity); 
false 

_.any([null], _.identity); 
false 

這一結果更有意義(在我的頭上)

null === _.identity(null); 
true 
+0

您不會將null與null進行比較,您會將null與true進行比較,即false – dandavis

回答

1

every沒有做任何的比較,只是希望能夠返回truthy/falsy值。 null是虛假的。從MDN上內置every

的每一個方法,一旦執行該提供的回調函數爲每個數組中存在的 元件,直到它找到一個其中回調返回 一個falsy值(即變爲假的值當轉換爲布爾型的 時)。如果找到這樣的元素,立即 的每種方法都返回false。否則,如果回調函數爲所有 元素返回真值,則每個元素都將返回true。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

1

_.every_.any語義,這些應該出來false

語義。

_.every(arr, predicate) === true iff∀ x ∈ arr:predicate(x)

  • 換句話說,表達式的值爲true當且僅當在arr滿足predicate(從表達式真值函數)每元件。

_.any(arr, predicate) === true IFF ∃ X ∈ ARR:predicate(x)

  • 換句話說,表達式的值爲true當且僅當一個元件在arr滿足predicate至少。

申請。

_.every([null], _.identity)

  • _.identity(null)
  • null
  • false

_.any([null], _.identity)

  • [null].some(_.identity)
  • false(因爲¬ ∃ X ∈ {null}_.identity(x))。