我想比较两个数组。。。理想地、有效地。没有什么稀奇古怪的,如果它们是相同的,那就是真的,如果不是,那就是假的。毫不奇怪,比较运算符似乎不起作用。
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对每个数组进行编码,但是否有一种更快或“更好”的方法来简单地比较数组而不必遍历每个值?
以下是我的解决方案:
/**
* Tests two data structures for equality
* @param {object} x
* @param {object} y
* @returns {boolean}
*/
var equal = function(x, y) {
if (typeof x !== typeof y) return false;
if (x instanceof Array && y instanceof Array && x.length !== y.length) return false;
if (typeof x === 'object') {
for (var p in x) if (x.hasOwnProperty(p)) {
if (typeof x[p] === 'function' && typeof y[p] === 'function') continue;
if (x[p] instanceof Array && y[p] instanceof Array && x[p].length !== y[p].length) return false;
if (typeof x[p] !== typeof y[p]) return false;
if (typeof x[p] === 'object' && typeof y[p] === 'object') { if (!equal(x[p], y[p])) return false; } else
if (x[p] !== y[p]) return false;
}
} else return x === y;
return true;
};
适用于任何嵌套的数据结构,显然忽略了对象的方法。甚至不要考虑用这个方法扩展Object.prototype,当我尝试过一次时,jQuery坏了;)
对于大多数阵列,它仍然比大多数串行化解决方案更快。这可能是对象记录数组最快的比较方法。
递归在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"]]]
));;