<分区>
正如标题所说,我想比较两个js数组,我只关心内容是否相同,但我不关心它们的顺序是否相同。所以我期望的是:
[1, 2, 3, 3] == [1, 2, 3, 3] // True
[1, 2, 3, 3] == [1, 3, 2, 3] // True
[1, 2, 3, 3] == [1, 2] // False
[1, 2, 3, 3] == [1, 2, 3] // False
[1, 2, 3, 3] == [1, 2, 3, 3, 3] // False
[1, 2, 3, 3] == [1, "2, 3, 3"] // False
显然比较运算符不起作用。来自 this SO answer我得到了下面的 Array.prototype 方法,但不幸的是,它也会检查顺序是否相同。
那么有人知道我如何检查两个 js 数组是否包含相同的元素,而不考虑元素的顺序吗?欢迎所有提示!
Array.prototype.equals = function (array) {
// if the other array is a falsy value, return
if (!array)
return false;
// compare lengths - can save a lot of time
if (this.length != array.length)
return false;
for (var i = 0, l=this.length; i < l; i++) {
// Check if we have nested arrays
if (this[i] instanceof Array && array[i] instanceof Array) {
// recurse into the nested arrays
if (!this[i].equals(array[i]))
return false;
}
else if (this[i] != array[i]) {
// Warning - two different object instances will never be equal: {x:20} != {x:20}
return false;
}
}
return true;
}