本文介绍了jQuery检查两个数组是否至少具有一个公共元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用JQuery检查两个数组是否至少有一个公共元素并返回true.以下行无法按我的意愿工作:
I want to check with JQuery if two arrays have at least one common element and return true. Following line does not work as I want:
if(jQuery.inArray(array1,array2) > -1) {return true;}
您能帮我找到解决方法吗?
Could you please help me to find the solution.
推荐答案
一种方法是循环遍历一个数组,并为第二个数组使用$ .inArray.
One way to do this is to loop through one array and use $.inArray for the second array..
function hasCommonElement(arr1,arr2)
{
var bExists = false;
$.each(arr2, function(index, value){
if($.inArray(value,arr1)!=-1){
console.log(value);
bExists = true;
}
if(bExists){
return false; //break
}
});
return bExists;
}
现在我们可以检查
if(hasCommonElement(arr1,arr2)){
return true;
}
希望会有更好的答案...
Hopefully there would be a better answer...
这篇关于jQuery检查两个数组是否至少具有一个公共元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!