如何检查是否一个JavaScript数组中存在多个值 [英] How to check whether multiple values exist within an Javascript array
问题描述
所以,我使用jQuery,并且都具有多个值,我想检查是否全部第一个数组中的值在第二个存在。
两个数组有关实例,例如1 ...
数组A包含下列值
34,78,89
数组b中包含以下值
78,67,34,99,56,89
这将返回真正
块引用>...示例2:
数组A包含下列值
34,78,89
数组b中包含以下值
78,67,99,56,89
这将返回假
块引用>...例子3:
数组A包含下列值
34,78,89
数组b中包含以下值
78,89
这将返回假
块引用>到目前为止,我已经试图解决这个:
- 使用自定义的比较的方法比较两个阵列。问题是,这只是回报真正当阵列是相同的,因为你可以从例如1见我希望它返回true,即使它们不相同,但至少包含值
- 使用 Jquerys .inArray功能,但对于一个值在数组中此只检查,而不是多个。
这是任何人都可以扔在这的任何光线将是巨大的。
解决方案函数containsAll(针,干草堆){
对于(VAR I = 0,LEN = needles.length; I< LEN,我++){
如果($ inArray(针[I],草垛)== -1)返回false;
}
返回true;
}containsAll([34,78,89],[78,67,34,99,56,89]); //真
containsAll([34,78,89],[78,67,99,56,89]); //假
containsAll([34,78,89],[78,89]); //假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.
For instance, example 1...
Array A contains the following values
34, 78, 89
Array B contains the following values
78, 67, 34, 99, 56, 89
This would return true
...example 2:
Array A contains the following values
34, 78, 89
Array B contains the following values
78, 67, 99, 56, 89
This would return false
...example 3:
Array A contains the following values
34, 78, 89
Array B contains the following values
78, 89
This would return false
So far I have tried to solve this by:
- 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
- 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 , len = needles.length; i < len; 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
这篇关于如何检查是否一个JavaScript数组中存在多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!