我希望在 javascript 中有一个函数(如果可能的话,使用 jQuery),它允许我将 ids 数组传递到函数中,并检查是否在另一个数组中找到每个值以返回 TRUE。
例如
var ids1 = [1, 6, 9, 11, 20];
var ids2 = [5, 6, 9, 11];
function check_array(ids)
{
var search = [1, 6, 9, 11, 20];
// do some checking here
// if all ids are matched up return TRUE;
// otherwise return FALSE;
}
在此实例中 - 第一个 var ids1 将返回 TRUE,而第二个 var ids2 将返回 FALSE。
任何人都可以建议最简单/最干净的方法吗?
最佳答案
function check_array(ids1, ids2) {
return $(ids1).not(ids2).get().length === 0;
}
var ids1 = [1, 6, 9, 11, 20];
var ids2 = [5, 6, 9, 11];
console.log(check_array(ids1, ids2)); // false
console.log(check_array(ids2, ids1)); // false
var search = [1, 6, 9, 11, 20];
console.log(check_array(search, ids2)); // false
console.log(check_array(search, ids1)); // true
虽然上面的通用版本已经足够了,但这正是您所要求的:
function check_array(ids) {
var search = [1, 6, 9, 11, 20];
return $(search).not(ids).get().length === 0;
}
var ids1 = [1, 6, 9, 11, 20];
var ids2 = [5, 6, 9, 11];
console.log(check_array(ids1)); // true
console.log(check_array(ids2)); // false
关于javascript - 如何使用 javascript/jQuery 检查数组中的所有项目是否匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17297871/