我需要比较两个数组中的元素,如下所示:
arr1[0] ? arr2[0]
arr1[1] ? arr2[1]
arr1[2] ? arr2[2]
etc.
我写了一些代码,但是当我尝试在每个数组上比较1000个这样的对象时似乎很慢:
{
"id":"event707",
"name":"Custom707",
"type":"disabled",
"default_metric":false,
"participation":"disabled",
"serialization":"always_record"
}
这就是我的函数的样子(只是两个带有硬编码数据的数组的例子)。
function compare() {
var step = 0;
var fruits1 = [{"apple":25},{"bannana":36},{"orange":6}];
var fruits2 = [{"apple":25},{"bannana":36},{"orange":6}];
for(var i=0;i<fruits1.length;i++) {
for(var j=step;j<fruits2.length;j++) {
console.log("FRUIT1");
console.log(JSON.stringify(fruits1[i]));
console.log("FRUIT2");
console.log(JSON.stringify(fruits2[j]));
console.log("----------------------");
if(JSON.stringify(fruits1[i])!== JSON.stringify(fruits2[j])) {
//do something
}
step = step + 1;
break;
}
}
}
答案 0 :(得分:1)
没有库的简单功能:
var arr1 = [1,2,3];
var arr2 = [1,2,4];
//This function takes one item, the index of the item, and another array to compare the item with.
function compare(item, index, array2){
return array2[index] == item;
}
// the forEach method gives the item as first parameter
// the index as second parameter
// and the array as third parameter. All are optional.
arr1.forEach(function(item, index){
console.log(compare(item, index, arr2));
});
将此与Abdennour TOUMI
给出的答案相结合,并且您有一个对象比较方法:)
对于简单对象,您可以使用JSON.stringify(obj1) === JSON.stringify(obj2)
。
可以找到有关对象比较的更多信息in this answer
答案 1 :(得分:1)
随着DELIMITER $$$
CREATE EVENT autoDayInsert ON SCHEDULE EVERY 15 DAY DO BEGIN
SET @dayCounter = 0;
WHILE @dayCounter < 15 DO
INSERT INTO appointmentDays(`day`) VALUES(NOW() + INTERVAL @dayCounter DAY);
SET @dayCounter = @dayCounter +1;
END WHILE;
END $$$
DELIMITER ;
和Object.prototype.compare()
的发明,这项工作变得非常简单。数组比较可以处理基本类型项和引用类型项。对象比较浅。让我们看看它是如何运作的;
Array.prototype.compare()
&#13;
答案 2 :(得分:0)
使用下划线数组函数。我会去路口
答案 3 :(得分:0)
您可以对static
课程使用以下Object
方法: Object.equals
Object.equals=function(a,b){if(a===b)return!0;if(!(a instanceof Object&&b instanceof Object))return!1;if(a.valueOf()===b.valueOf())return!0;if(a.constructor!==b.constructor)return!1;for(var c in a)if(a.hasOwnProperty(c)){if(!b.hasOwnProperty(c))return!1;if(a[c]!==b[c]){if("object"!=typeof a[c])return!1;if(!Object.equals(a[c],b[c]))return!1}}for(c in b)if(b.hasOwnProperty(c)&&!a.hasOwnProperty(c))return!1;return!0};
console.log(
`"[1,2,3] == [1,2,3]" ?`,Object.equals([1,2,3],[1,2,3])
);
console.log(
`"[{"apple":25},{"bannana":36},{"orange":6}] == [{"apple":25},{"bannana":36},{"orange":6}]" ?`,Object.equals([{"apple":25},{"bannana":36},{"orange":6}], [{"apple":25},{"bannana":36},{"orange":6}])
);
&#13;