UnderscoreJS _.every 用于空值

UnderscoreJS _.every for nulls

似乎 null 应该等于 null。那么为什么

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

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

这个结果更有意义(在我看来)

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

every 没有进行任何比较,它只是希望返回一个 truthy/falsy 值。 null 是假的。来自内置 every:

上的 MDN

The every method executes the provided callback function once for each element present in the array until it finds one where callback returns a falsy value (a value that becomes false when converted to a Boolean). If such an element is found, the every method immediately returns false. Otherwise, if callback returned a true value for all elements, every will return true.

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

根据_.every and _.any的语义,应该是false:

语义。

_.every(arr, predicate) === true当且仅当∀x∈到达:predicate(x).

  • 换句话说,当且仅当 arr 中的 每个 元素满足 predicate (函数从表达式到真值)。

_.any(arr, predicate) === true 当且仅当 ∃x ∈到达:predicate(x).

  • 换句话说,当且仅当 arr 中的至少一个 元素满足 predicate 时,表达式的计算结果为 true

申请.

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

  • _.identity(null)
  • null
  • false.

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

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