我想比较两个数组。。。理想地、有效地。没有什么稀奇古怪的,如果它们是相同的,那就是真的,如果不是,那就是假的。毫不奇怪,比较运算符似乎不起作用。
var a1 = [1,2,3];
var a2 = [1,2,3];
console.log(a1==a2); // Returns false
console.log(JSON.stringify(a1)==JSON.stringify(a2)); // Returns true
JSON对每个数组进行编码,但是否有一种更快或“更好”的方法来简单地比较数组而不必遍历每个值?
在我的例子中,比较数组只包含数字和字符串。此函数将显示数组是否包含相同的元素。
function are_arrs_match(arr1, arr2){
return arr1.sort().toString() === arr2.sort().toString()
}
让我们测试一下!
arr1 = [1, 2, 3, 'nik']
arr2 = ['nik', 3, 1, 2]
arr3 = [1, 2, 5]
console.log (are_arrs_match(arr1, arr2)) //true
console.log (are_arrs_match(arr1, arr3)) //false
与嵌套数组一起使用MULTIPLE参数:
//:Return true if all of the arrays equal.
//:Works with nested arrays.
function AllArrEQ(...arrays){
for(var i = 0; i < (arrays.length-1); i++ ){
var a1 = arrays[i+0];
var a2 = arrays[i+1];
var res =(
//:Are both elements arrays?
Array.isArray(a1)&&Array.isArray(a2)
?
//:Yes: Compare Each Sub-Array:
//:v==a1[i]
a1.every((v,i)=>(AllArrEQ(v,a2[i])))
:
//:No: Simple Comparison:
(a1===a2)
);;
if(!res){return false;}
};;
return( true );
};;
console.log( AllArrEQ(
[1,2,3,[4,5,[6,"ALL_EQUAL" ]]],
[1,2,3,[4,5,[6,"ALL_EQUAL" ]]],
[1,2,3,[4,5,[6,"ALL_EQUAL" ]]],
[1,2,3,[4,5,[6,"ALL_EQUAL" ]]],
));;
虽然这个问题的最佳答案是正确和良好的,但提供的代码可能需要一些改进。
下面是我自己比较数组和对象的代码。代码简短而简单:
Array.prototype.equals = function(otherArray) {
if (!otherArray || this.length != otherArray.length) return false;
return this.reduce(function(equal, item, index) {
var otherItem = otherArray[index];
var itemType = typeof item, otherItemType = typeof otherItem;
if (itemType !== otherItemType) return false;
return equal && (itemType === "object" ? item.equals(otherItem) : item === otherItem);
}, true);
};
if(!Object.prototype.keys) {
Object.prototype.keys = function() {
var a = [];
for (var key in this) {
if (this.hasOwnProperty(key)) a.push(key);
}
return a;
}
Object.defineProperty(Object.prototype, "keys", {enumerable: false});
}
Object.prototype.equals = function(otherObject) {
if (!otherObject) return false;
var object = this, objectKeys = object.keys();
if (!objectKeys.equals(otherObject.keys())) return false;
return objectKeys.reduce(function(equal, key) {
var value = object[key], otherValue = otherObject[key];
var valueType = typeof value, otherValueType = typeof otherValue;
if (valueType !== otherValueType) return false;
// this will call Array.prototype.equals for arrays and Object.prototype.equals for objects
return equal && (valueType === "object" ? value.equals(otherValue) : value === otherValue);
}, true);
}
Object.defineProperty(Object.prototype, "equals", {enumerable: false});
此代码支持嵌套在对象中的数组和嵌套在数组中的对象。
您可以在下面的repl中看到一整套测试并自己测试代码:https://repl.it/Esfz/3