首页 > 解决方案 > 为什么 Array.prototype.some() 不为空集返回 true?

问题描述

我刚刚在 MDN 页面上找到了这篇文章Array.prototype.every()

every就像数学中的“所有人”量词。特别是,对于一个空数组,它返回 true。(空集的所有元素都满足任何给定条件,这是毫无意义的。

确实如此,我们可以看到:

console.log([].every(a => a === "any possible value here"))

然而:

console.log([].some(a => a === "any possible value here"))

问题:

冒着被关闭为基于意见的风险,这是我的问题:为什么 ECMA 不选择将Array.prototype.some()的回调视为空数组的空数组?

在我看来,如果“空集的所有元素满足任何给定条件是空洞的”,正如 MDN 页面所说,那么“空集的任何元素满足任何给定的条件都是空洞的”条件”。例如,如果我们使用维基百科的例子,

房间里的所有手机都打开和关闭

我们可以说“房间里的一些手机已关闭”同样(并且毫无意义)是正确的。不是这样吗?

标签: javascript

解决方案


With .every, you're asking whether all items in a list fulfil a condition. If that list is empty, well, there are no items which do not fulfil the condition. Every item that there is (which is none) fulfils the given condition, so .every is vacuously true.

With .some, you're asking whether any item in a list fulfils a condition. If there are no items, then there's no item to fulfil the condition. So no, nothing in an empty list can fulfil the condition and it's vacuously false.


推荐阅读