问题描述
给定两个二维数组,我如何断言它们是否相等?
Given two 2D arrays, how can I assert whether or not they are equal?
例如:
array1 = [[1,0],[2,1],[3,0]]
array2 = [[1,0],[2,1],[3,1]]
检查 array1 == array2 的有效方法是什么?
What is an efficient way to check whether array1 == array2?
推荐答案
如果相等是指数组内容具有相同顺序的相同元素,那么最短(虽然不是最快)的方法是:
If by equality you mean the array contents have same elements in the same order, then the shortest (though not the fastest) way will be:
JSON.stringify(array1) === JSON.stringify(array2)
这适用于任何维度的数组.
This will work with arrays of any dimensions.
更新:如果你需要一个非常快速的算法,那么简单的迭代会更好.然而,它不是万无一失的,因此要使其真正安全可靠,您需要花费更多的开发时间.以下是现代浏览器的一种可能解决方案:
UPDATE: If you need a really fast algorithm then simple iteration will work better. However it is less fool-proof, hence to make it really safe and secure you'll need to spend more development time. Here is one possible solution for modern browsers:
function equal(array1, array2) {
if (!Array.isArray(array1) && !Array.isArray(array2)) {
return array1 === array2;
}
if (array1.length !== array2.length) {
return false;
}
for (var i = 0, len = array1.length; i < len; i++) {
if (!equal(array1[i], array2[i])) {
return false;
}
}
return true;
}
以下 JSPerf 速度测试显示了该算法相对于简短的 JSON
方法的优越性:http://jsperf.com/2d-array-comparion.
The following JSPerf speed test shows the supremacy of this algorithm over the short JSON
approach: http://jsperf.com/2d-array-comparion.
这篇关于断言两个二维数组是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!