我想比较两个数组。。。理想地、有效地。没有什么稀奇古怪的,如果它们是相同的,那就是真的,如果不是,那就是假的。毫不奇怪,比较运算符似乎不起作用。
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对每个数组进行编码,但是否有一种更快或“更好”的方法来简单地比较数组而不必遍历每个值?
let equals = (LHS, RHS) => {
if (!(LHS instanceof Array)) return "false > L.H.S is't an array";
if (!(RHS instanceof Array)) return "false > R.H.S is't an array";
if (LHS.length != RHS.length) return false;
let to_string = x => JSON.stringify(x.sort((a, b) => a - b));
return to_string(LHS) == to_string(RHS);
};
let l = console.log
l(equals([5,3,2],[3,2,5])) // true
l(equals([3,2,5,3],[3,2,5])) // false
这里有很多复杂的长答案,所以我只想提供一个非常简单的答案:使用toString()将数组转换为简单的逗号分隔字符串===
let a = [1, 2, 3]
let b = [1, 2, 3]
let c = [4, 2, 3]
console.log(a.toString()) // this outputs "1,2,3"
console.log(a.toString() === b.toString()) // this outputs true because "1,2,3" === "1,2,3"
console.log(a.toString() === c.toString()) // this outputs false because "1,2,3" != "4,2,3"
递归在NESTED数组上工作(&W):
function ArrEQ(a1,a2){
return(
//:Are both elements arrays?
Array.isArray(a1)&&Array.isArray(a2)
?
//:Yes: Test each entry for equality:
a1.every((v,i)=>(ArrEQ(v,a2[i])))
:
//:No: Simple Comparison:
(a1===a2)
);;
};;
console.log( "Works With Nested Arrays:" );
console.log( ArrEQ(
[1,2,3,[4,5,[6,"SAME/IDENTICAL"]]],
[1,2,3,[4,5,[6,"SAME/IDENTICAL"]]]
));;
console.log( ArrEQ(
[1,2,3,[4,5,[6,"DIFFERENT:APPLES" ]]],
[1,2,3,[4,5,[6,"DIFFERENT:ORANGES"]]]
));;