在 JavaScript 中,如何测试一个数组是否包含另一个数组的元素?
arr1 = [1, 2, 3, 4, 5]
[8, 1, 10, 2, 3, 4, 5, 9].function_name(arr1) # => true
在 JavaScript 中,如何测试一个数组是否包含另一个数组的元素?
arr1 = [1, 2, 3, 4, 5]
[8, 1, 10, 2, 3, 4, 5, 9].function_name(arr1) # => true
没有 set 函数可以做到这一点,但您可以简单地做一个临时数组交集并检查长度。
[8, 1, 10, 2, 3, 4, 5, 9].filter(function (elem) {
return arr1.indexOf(elem) > -1;
}).length == arr1.length
一种更有效的方法是使用.every
which 将在虚假情况下短路。
arr1.every(elem => arr2.indexOf(elem) > -1);
您可以使用array.indexOf():
伪代码:
function arrayContainsAnotherArray(needle, haystack){
for(var i = 0; i < needle.length; i++){
if(haystack.indexOf(needle[i]) === -1)
return false;
}
return true;
}
function arr(arr1,arr2)
{
for(var i=0;i<arr1.length;i++)
{
if($.inArray(arr1[i],arr2) ==-1)
//here it returns that arr1 value does not contain the arr2
else
// here it returns that arr1 value contains in arr2
}
}
ES6 解决方案使用includes
:
[1].every(elem => [1,2,3].includes(elem));
与上面的 Explosion Pills 的解决方案非常相似,只是更具可读性(并且可以说是慢了一点点)。
I faced the same case if I got you exactly, my case was to check visited places while one trip, every trip have its own point and we have a data for all working area places, here is the code maybe help you.