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