Javascript 如何以最有效的方式检查相同的数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4025893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check identical array in most efficient way?
提问by ssdesign
I want to check if the two arrays are identical (not content wise, but in exact order).
我想检查两个数组是否相同(不是内容明智,但顺序完全相同)。
For example:
例如:
array1 = [1,2,3,4,5]
array2 = [1,2,3,4,5]
array3 = [3,5,1,2,4]
Array 1 and 2 are identical but 3 is not.
数组 1 和 2 相同,但数组 3 不同。
Is there a good way to do this in JavaScript?
在 JavaScript 中是否有一种好方法可以做到这一点?
回答by palswim
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;
}
回答by Adam
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
如果这对您很重要,则等于 array1