我想比较两个数组。。。理想地、有效地。没有什么稀奇古怪的,如果它们是相同的,那就是真的,如果不是,那就是假的。毫不奇怪,比较运算符似乎不起作用。
var a1 = [1,2,3];
var a2 = [1,2,3];
console.log(a1==a2); // Returns false
console.log(JSON.stringify(a1)==JSON.stringify(a2)); // Returns true
JSON对每个数组进行编码,但是否有一种更快或“更好”的方法来简单地比较数组而不必遍历每个值?
所有其他解决方案看起来都很复杂。这可能不是处理所有边缘情况的最有效方法,但它对我来说非常有用。
Array.prototype.includesArray = function(arr) {
return this.map(i => JSON.stringify(i)).includes(JSON.stringify(arr))
}
用法
[[1,1]].includesArray([1,1])
// true
[[1,1]].includesArray([1,1,2])
// false
如果它们是两个数字或字符串数组,这是一个快速的单行数组
const array1 = [1, 2, 3];
const array2 = [1, 3, 4];
console.log(array1.join(',') === array2.join(',')) //false
const array3 = [1, 2, 3];
const array4 = [1, 2, 3];
console.log(array3.join(',') === array4.join(',')) //true
这里有很多复杂的长答案,所以我只想提供一个非常简单的答案:使用toString()将数组转换为简单的逗号分隔字符串===
let a = [1, 2, 3]
let b = [1, 2, 3]
let c = [4, 2, 3]
console.log(a.toString()) // this outputs "1,2,3"
console.log(a.toString() === b.toString()) // this outputs true because "1,2,3" === "1,2,3"
console.log(a.toString() === c.toString()) // this outputs false because "1,2,3" != "4,2,3"