如何以最有效的方式检查同一数组?

我想检查两个数组是否相同 (不是内容明智,而是按照确切的顺序)。

例如:

 array1 = [1,2,3,4,5]
array2 = [1,2,3,4,5]
array3 = [3,5,1,2,4]

数组1和2是相同的,但3不是。

有没有用 JavaScript 实现这一点的好方法?

119310 次浏览

You could compare String representations so:

array1.toString() == array2.toString()
array1.toString() !== array3.toString()

but that would also make

array4 = ['1',2,3,4,5]

equal to array1 if that matters to you

So, what's wrong with checking each element iteratively?

function arraysEqual(arr1, arr2) {
if(arr1.length !== arr2.length)
return false;
for(var i = arr1.length; i--;) {
if(arr1[i] !== arr2[i])
return false;
}


return true;
}