如何在JavaScript中比较数组?

2022-08-29 22:01:48

我想比较两个数组...理想情况下,高效。没什么花哨的,只是如果它们是相同的,如果不是。毫不奇怪,比较运算符似乎不起作用。truefalse

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编码每个数组都可以,但是有没有更快或“更好”的方法来简单地比较数组而不必迭代每个值?


答案 1

要比较数组,请遍历它们并比较每个值:

比较数组:

// Warn if overriding existing method
if(Array.prototype.equals)
    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.");
// attach the .equals method to Array's prototype to call it on any array
Array.prototype.equals = function (array) {
    // if the other array is a falsy value, return
    if (!array)
        return false;

    // compare lengths - can save a lot of time 
    if (this.length != array.length)
        return false;

    for (var i = 0, l=this.length; i < l; i++) {
        // Check if we have nested arrays
        if (this[i] instanceof Array && array[i] instanceof Array) {
            // recurse into the nested arrays
            if (!this[i].equals(array[i]))
                return false;       
        }           
        else if (this[i] != array[i]) { 
            // Warning - two different object instances will never be equal: {x:20} != {x:20}
            return false;   
        }           
    }       
    return true;
}
// Hide method from for-in loops
Object.defineProperty(Array.prototype, "equals", {enumerable: false});

用法:

[1, 2, [3, 4]].equals([1, 2, [3, 2]]) === false;
[1, "2,3"].equals([1, 2, 3]) === false;
[1, 2, [3, 4]].equals([1, 2, [3, 4]]) === true;
[1, 2, 1, 2].equals([1, 2, 1, 2]) === true;

你可能会说“但是比较字符串要快得多 - 没有循环......”好吧,那么你应该注意有ARE循环。第一个递归循环将 Array 转换为字符串,第二个递归循环比较两个字符串。所以这种方法比使用字符串更快

我认为应该始终将大量数据存储在数组中,而不是存储在对象中。但是,如果您使用对象,也可以对它们进行部分比较。
操作方法如下:

比较对象:

我在上面已经说过,两个对象实例永远不会相等,即使它们目前包含相同的数据:

({a:1, foo:"bar", numberOfTheBeast: 666}) == ({a:1, foo:"bar", numberOfTheBeast: 666})  //false

这是有原因的,因为例如对象中可能存在私有变量。

但是,如果您只使用对象结构来包含数据,则仍然可以进行比较:

Object.prototype.equals = function(object2) {
    //For the first loop, we only check for types
    for (propName in this) {
        //Check for inherited methods and properties - like .equals itself
        //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
        //Return false if the return value is different
        if (this.hasOwnProperty(propName) != object2.hasOwnProperty(propName)) {
            return false;
        }
        //Check instance type
        else if (typeof this[propName] != typeof object2[propName]) {
            //Different types => not equal
            return false;
        }
    }
    //Now a deeper check using other objects property names
    for(propName in object2) {
        //We must check instances anyway, there may be a property that only exists in object2
            //I wonder, if remembering the checked values from the first loop would be faster or not 
        if (this.hasOwnProperty(propName) != object2.hasOwnProperty(propName)) {
            return false;
        }
        else if (typeof this[propName] != typeof object2[propName]) {
            return false;
        }
        //If the property is inherited, do not check any more (it must be equa if both objects inherit it)
        if(!this.hasOwnProperty(propName))
          continue;
        
        //Now the detail check and recursion
        
        //This returns the script back to the array comparing
        /**REQUIRES Array.equals**/
        if (this[propName] instanceof Array && object2[propName] instanceof Array) {
                   // recurse into the nested arrays
           if (!this[propName].equals(object2[propName]))
                        return false;
        }
        else if (this[propName] instanceof Object && object2[propName] instanceof Object) {
                   // recurse into another objects
                   //console.log("Recursing to compare ", this[propName],"with",object2[propName], " both named \""+propName+"\"");
           if (!this[propName].equals(object2[propName]))
                        return false;
        }
        //Normal value comparison for strings and numbers
        else if(this[propName] != object2[propName]) {
           return false;
        }
    }
    //If everything passed, let's say YES
    return true;
}  

但是,请记住,这是为了比较JSON(如数据),而不是类实例和其他东西。如果你想比较更复杂的对象,看看这个答案,它是超长函数
要使此功能正常工作,您必须稍微编辑一下原始函数:Array.equals

...
    // Check if we have nested arrays
    if (this[i] instanceof Array && array[i] instanceof Array) {
        // recurse into the nested arrays
        if (!this[i].equals(array[i]))
            return false;
    }
    /**REQUIRES OBJECT COMPARE**/
    else if (this[i] instanceof Object && array[i] instanceof Object) {
        // recurse into another objects
        //console.log("Recursing to compare ", this[propName],"with",object2[propName], " both named \""+propName+"\"");
        if (!this[i].equals(array[i]))
            return false;
        }
    else if (this[i] != array[i]) {
...

为这两个功能做了一个小测试工具

奖励:嵌套数组与 和indexOfcontains

Samy Bencherif 为您在嵌套数组中搜索特定对象的情况准备了有用的函数,这些函数可在此处找到:https://jsfiddle.net/SamyBencherif/8352y6yw/


答案 2

虽然这仅适用于标量数组(请参阅下面的注释),但它是短代码:

array1.length === array2.length && array1.every(function(value, index) { return value === array2[index]})

与上面相同,但在 ECMAScript 6 / CoffeeScript / TypeScript with Arrow Functions 中:

array1.length === array2.length && array1.every((value, index) => value === array2[index])

(注意:此处的“标量”是指可以使用 直接比较的值。所以:数字,字符串,引用对象,引用函数。有关比较运算符的详细信息,请参阅 MDN 参考)。===

更新

根据我在评论中读到的内容,对数组进行排序并进行比较可能会给出准确的结果:

const array2Sorted = array2.slice().sort();
array1.length === array2.length && array1.slice().sort().every(function(value, index) {
    return value === array2Sorted[index];
});

例如:

array1 = [2,3,1,4];
array2 = [1,2,3,4];

然后上面的代码将返回true