正在使用另一个数组检查数组中的多个值

Checking multiple values in array with another array

本文关键字:数组 检查 另一个      更新时间:2023-11-30

我有一个从JSON数据中获得的对象A数组,如下所示:

[Object { field1="2381", field2="1233", field3="46.44852", more...},
Object { field1="2381", field2="1774", field3="45.70752833333334", more...}]

我有另一个类似的B阵列

["2381", "1187"]

有没有办法检查这个数组B的值是否存在于数组A中?

我试过类似的东西

A.map((B[0], B[1]), function(element) {
    if (B[0] == element.field1 && B[1] == element.field2) 
        return true; 
    else 
        return false; 
});

但效果并不好。。。

有什么窍门吗?

查看A中是否至少有一项与B匹配。

A.some(function(value) {
    return value.field1 == B[0] && value.field2 == B[1];
});

您可以使用嵌套的for循环。大致如下:

 var checker; //number to hold the current value
for(x=0;x<arrayA.length; x++) //loop through the first array
{
  checker = arrayA[x]; store the number in each element in the variable
 for(y=array.Indexof(arrayA, checker);y<arrayB.length; y++) /*don't start from the very first index of the array but rather from the last place where arrayA was*/
  {
   if (arrayB[y] == checker)
     {
   Alert(checker + " is the same");
 }//closes if
}//closes for
}//closes outer for loop

很明显,你会根据自己的特殊需求来代替警报。我的语法可能有点偏离,但你明白要点了。希望这能帮助。。。

您可以使用这样的函数:

function check(arr, fn) {
    var i = 0, l = arr.length;
    for (; i < l; i++) {
        if (fn(arr[i])) return true;
    }
    return false;
}

用法:

var A, B;
A = [
    { field1: 1, field2: 2 },
    { field1: 1, field2: 3 },
    { field1: 2, field2: 3 }
];
B = [1, 3];
check(A, function (item) {
    return item.field1 === B[0] && item.field2 === B[1];
}); // true
B = [2, 1];
check(A, function (item) {
    return item.field1 === B[0] && item.field2 === B[1];
}); // false