正在使用另一个数组检查数组中的多个值
Checking multiple values in array with another array
我有一个从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
相关文章:
- 使用Javascript使用数组检查文本框中的值
- JS数组-检查对象值是否重复
- Ruby数组检查并替换为
- 根据数组检查输入变量
- 根据字符串数组检查字符串(密码验证)
- 如何按数组检查字符串是否具有匹配的子字符串
- 多维布尔数组检查 Javascript 中是否全部为真
- 如何根据值数组检查当前窗口位置
- JavaScript多维数组检查
- Javascript 2D数组检查Div类
- JavaScript-用数组检查字符串
- 在for循环数组检查和JSON变量方面遇到问题
- 数组检查,然后是forEach()
- jQuery,根据数组检查类
- JavaScript根据数组检查textfield
- 根据javascript数组检查文本框值
- 根据数组检查值并返回另一个值
- Javascript数组检查
- Javascript数组检查值并分配到数组中
- JavaScript多维数组检查重复