在 JavaScript/CoffeeScript 中确定一个数组是否包含另一个数组的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15514907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:03:09  来源:igfitidea点击:

Determining whether one array contains the contents of another array in JavaScript/CoffeeScript

javascriptarrayscoffeescript

提问by Zeck

In JavaScript, how do I test that one array has the elements of another array?

在 JavaScript 中,如何测试一个数组是否具有另一个数组的元素?

arr1 = [1, 2, 3, 4, 5]
[8, 1, 10, 2, 3, 4, 5, 9].function_name(arr1) # => true

回答by Explosion Pills

No set function does this, but you can simply do an ad-hoc array intersection and check the length.

没有 set 函数会这样做,但您可以简单地进行临时数组交集并检查长度。

[8, 1, 10, 2, 3, 4, 5, 9].filter(function (elem) {
    return arr1.indexOf(elem) > -1;
}).length == arr1.length

A more efficient way to do this would be to use .everywhich will short circuit in falsy cases.

一种更有效的方法是使用.everywhich 将在虚假情况下短路。

arr1.every(elem => arr2.indexOf(elem) > -1);

回答by valentinas

You can use array.indexOf():

您可以使用array.indexOf()

pseudocode:

伪代码:

function arrayContainsAnotherArray(needle, haystack){
  for(var i = 0; i < needle.length; i++){
    if(haystack.indexOf(needle[i]) === -1)
       return false;
  }
  return true;
}

回答by tamilmani

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

     }

}