[英]Compare two arrays in javascript
I'd like to check which elements are equal in my two arrays, but can't get it working. 我想检查两个数组中哪些元素相等,但是无法正常工作。
This is my code: 这是我的代码:
for (var i; i < bombs.length; i++) {
for (var j; j < bombsDb.length; j++) {
if (bombs[i].name === bombsDb[j].address) {
console.log(bombs[i].name);
} else {
console.log("non-equal elements");
}
}
}
So the first array contains objects from the google places api and the second one contains data from my database. 因此,第一个数组包含来自Google Places api的对象,第二个数组包含来自我的数据库的数据。
Thanks in advance! 提前致谢!
You have to initialize i
and j
; 您必须初始化i
和j
;
for (var i = 0; i < bombs.length; i++) {
for (var j = 0; j < bombsDb.length; j++) {
if (bombs[i].name === bombsDb[j].address) {
console.log(bombs[i].name);
} else {
console.log("non-equal elements");
}
}
}
Comparing can also be done using the .not
selector from jquery. 也可以使用jquery中的.not
选择器进行比较。 Check this: 检查一下:
var a = [1,2,3,4,5,6];
var b = [4,5,6,7,8,9];
$(a).not( $(a).not(b).get() ).get();
This will return the following array 这将返回以下数组
[4,5,6]
You are missing the initial assignment to i
and j
in your for loop. 您在for循环中缺少对i
和j
的初始分配。
// here
// v
for (var i = 0; i < bombs.length; i++) {
// your loop
}
This causes the comparision to return false in the first iteration of the loop since undefined < bombs.length
always return false, so it will not proceed. 这会导致比较在循环的第一次迭代中返回false,因为undefined < bombs.length
始终返回false,因此不会继续进行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.