[英]Check if all elements in an array are present in another
I want to make a function to check if all elements in an array are present in another. 我想做一个函数来检查数组中的所有元素是否存在于另一个数组中。 I have tried to do this:
我试图做到这一点:
function includesAll (needles, haystack) {
return needles.every((needle) => {
return haystack.includes(needle)
})
}
However, when I test for this function for the empty array as needles
, like this: includesAll([], [1])
, it returns true
, whereas I'm expecting false
(because [1].includes([])
returns false
). 但是,当我为
needles
测试空数组的此函数时,如下所示: includesAll([], [1])
,它返回true
,而我期望为false
(因为[1].includes([])
返回false
)。 Why does this happen? 为什么会这样? And can you write a correct function (one that reflects the behavior of
include
, but for an array instead of an element)? 并且可以编写一个正确的函数(一个反映
include
行为的函数,但反映数组而不是元素的函数)吗?
Your code is working as expected. 您的代码按预期工作。 The function should return true because there is no element in the empty needles array that is not included in the haystack.
该函数应返回true,因为干草堆中不包含空针阵列中没有的元素。
You wrote: 你写了:
because [1].includes([]) returns false
因为[1] .includes([])返回false
...but that is not the same, and is not happening either. ...但是那不一样,也不会发生。 The includes method is not passed the needles array, but elements in that array.
include方法不会传递needles数组,而是传递该数组中的元素。 And since there are none, includes is never called.
而且由于没有, 包括永远不会被调用。 The function should return
true
, as there is no element that is not included. 该函数应该返回
true
,因为没有不包含的元素。
If for some reason you want another behaviour, you could do as follows: 如果出于某种原因您想要其他行为,则可以执行以下操作:
function includesAll (needles, haystack) {
return !needles.length && needles.every(needle => haystack.includes(needle));
}
This way you require that the function can only return true
if needles has at least one element. 这样,您要求该函数仅在针具有至少一个元素的情况下才能返回
true
。
You have a flaw in your logic. 您的逻辑存在缺陷。 In your includesAll function, you are comparing two arrays.
在includesAll函数中,您正在比较两个数组。 As such,
因此,
includesAll([], [1]);
should return true
. 应该返回
true
。
This is not equivalent to checking 这不等于检查
[1].includes([]);
which is checking if the array [1]
contains an empty array, which it does not. 它正在检查数组
[1]
包含一个空数组,而没有。
In terms of your function, that would be like checking 就您的功能而言,这就像检查
includesAll([[]], [1]);
which should return false
应该返回
false
Read this at MDN 在MDN上阅读
every
acts like the "for all" quantifier in mathematics.every
行为都像数学中的“所有人”量词。 In particular, for an empty array, it returns true.特别是对于空数组,它返回true。 (It is vacuously true that all elements of the empty set satisfy any given condition.)
(空集的所有元素都满足任何给定条件是完全虚假的。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.