JavaScript如何比较两个数组的内容是否相同

alert([]==[]);    // false
alert([]===[]);   // false

以上两句代码都会弹出false。

因为JavaScript里面Array是对象,==或===操作符只能比较两个对象是否是同一个实例,也就是是否是同一个对象引用。目前JavaScript没有内置的操作符判断对象的内容是否相同。

但是惯性思维让人以为数组也是值,是可以比较的。

如果要比较数组是否相等,就只能遍历数组元素比较。

在网上流传很普遍的一种做法是将数组转换成字符串:

1
JSON.stringify(a1) == JSON.stringify(a2)

 或

1
a1.toString() == a2.toString()

请不要使用这种方法。

这种方法在某些情况下是可行的,当两个数组的元素顺序相同且元素都可以转换成字符串的情况下确实可行,但是这样的代码存有隐患,比如数字被转换成字符串,数字“1”和字符串“1”会被认为相等,可能造成调试困难,不推荐使用。

在StackOverflow上有大神已经提供了正确的方法,我就做下搬运工吧:

 1 // Warn if overriding existing method
 2 if(Array.prototype.equals)
 3     console.warn("Overriding existing Array.prototype.equals. Possible causes: New API defines the method, there's a framework conflict or you've got double inclusions in your code.");
 4 // attach the .equals method to Array's prototype to call it on any array
 5 Array.prototype.equals = function (array) {
 6     // if the other array is a falsy value, return
 7     if (!array)
 8         return false;
 9 
10     // compare lengths - can save a lot of time
11     if (this.length != array.length)
12         return false;
13 
14     for (var i = 0, l = this.length; i < l; i++) {
15         // Check if we have nested arrays
16         if (this[i] instanceof Array && array[i] instanceof Array) {
17             // recurse into the nested arrays
18             if (!this[i].equals(array[i]))
19                 return false;
20         }
21         else if (this[i] != array[i]) {
22             // Warning - two different object instances will never be equal: {x:20} != {x:20}
23             return false;
24         }
25     }
26     return true;
27 }
28 // Hide method from for-in loops
29 Object.defineProperty(Array.prototype, "equals", {enumerable: false});
1
const arr = [1]
2
const arr1 = ['1']
3
console.log(arr1.equals(arr));  //true

但是1和'1'不是同一种类型,我们希望类型不同时返回false

将上面代码的第11行和第21行的'!='改为'!=='即可

1
const arr = [1,2,3]
2
const arr1 = [1,2,3]
3
console.log(arr1.equals(arr))  //true

这么一看是没有问题的,但是如果我们将arr1中的内容改变一下顺序

1
const arr = [1,2,3]
2
const arr1 = [1,3,2]
3
console.log(arr1.equals(arr))  //false

打印的结果为false,但是我们希望即使顺序不同,也能返回true

那么就需要在比较之前分别对两个数据进行排序

在第五行后加入

1
const thisS = this.sort()
2
const arrayS = array.sort()

然后在代码中需要替换的地方将this和array替换成排序后的新数组

再次答应即可得到true

 

 引用文章:https://www.cnblogs.com/-867259206/p/6795354.html

原文地址:https://www.cnblogs.com/memeflyfly/p/14349267.html