如何检查Javascript数组中是否存在多个值

如何检查Javascript数组中是否存在多个值

问题描述:

所以,我正在使用 Jquery 并且有两个数组都具有多个值,我想检查第一个数组中的所有值是否存在于第二个数组中.

So, I'm using Jquery and have two arrays both with multiple values and I want to check whether all the values in the first array exist in the second.

例如,示例 1...

数组 A 包含以下值

34、78、89

数组 B 包含以下值

78、67、34、99、56、89

78, 67, 34, 99, 56, 89

这将返回 true

...示例 2:

数组 A 包含以下值

34、78、89

数组 B 包含以下值

78、67、99、56、89

78, 67, 99, 56, 89

这将返回 false

...示例 3:

数组 A 包含以下值

34、78、89

数组 B 包含以下值

78、89

这将返回 false

到目前为止,我已尝试通过以下方式解决此问题:

So far I have tried to solve this by:

  1. 使用自定义比较"方法扩展 Jquery 以比较两者数组.问题是这仅在数组相同时返回 true ,正如您从示例 1 中看到的那样,我希望它返回 true,即使它们不相同但至少包含值
  2. 使用 Jquerys .inArray 函数,但这只会检查数组中的一个值,不是多个.
  1. Extending Jquery with a custom 'compare' method to compare the two arrays. Problem is this only returns true when the arrays are identical and as you can see from example 1 I want it to return true even if they aren't identical but at least contain the value
  2. using Jquerys .inArray function, but this only checks for one value in an array, not multiple.

任何人都可以投在这上面的任何灯都会很棒.

Any light that anyone could throw on this would be great.

function containsAll(needles, haystack){ 
  for(var i = 0; i < needles.length; i++){
     if($.inArray(needles[i], haystack) == -1) return false;
  }
  return true;
}

containsAll([34, 78, 89], [78, 67, 34, 99, 56, 89]); // true
containsAll([34, 78, 89], [78, 67, 99, 56, 89]); // false
containsAll([34, 78, 89], [78, 89]); // false