如何检查两个数组是否与 JavaScript 相等?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3115982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:18:50  来源:igfitidea点击:

How to check if two arrays are equal with JavaScript?

javascript

提问by Koerr

var a = [1, 2, 3];
var b = [3, 2, 1];
var c = new Array(1, 2, 3);

alert(a == b + "|" + b == c);

demo

演示

How can I check these array for equality and get a method which returns trueif they are equal?

如何检查这些数组是否相等并获得一个方法,true如果它们相等则返回?

Does jQuery offer any method for this?

jQuery 是否为此提供任何方法?

回答by enyo

This is what you should do. Please don't use stringifynor < >.

这是你应该做的。请不要使用stringify< >

function arraysEqual(a, b) {
  if (a === b) return true;
  if (a == null || b == null) return false;
  if (a.length != b.length) return false;

  // If you don't care about the order of the elements inside
  // the array, you should sort both arrays here.
  // Please note that calling sort on an array will modify that array.
  // you might want to clone your array first.

  for (var i = 0; i < a.length; ++i) {
    if (a[i] !== b[i]) return false;
  }
  return true;
}

回答by ninjagecko

Option 1

选项1

Easiest option, works in almost all cases, except that null!==undefinedbut they both are converted to JSON representation nulland considered equal:

最简单的选项,几乎适用于所有情况,除了null!==undefined但它们都被转换为 JSON 表示null并被认为是相等的:

function arraysEqual(a1,a2) {
    /* WARNING: arrays must not contain {objects} or behavior may be undefined */
    return JSON.stringify(a1)==JSON.stringify(a2);
}

(This might not work if your array contains objects.Whether this still works with objects depends on whether the JSON implementation sorts keys. For example, the JSON of {1:2,3:4}may or may not be equal to {3:4,1:2}; this depends on the implementation, and the spec makes no guarantee whatsoever. [2017 update: Actually the ES6 specification now guarantees object keys will be iterated in order of 1) integer properties, 2) properties in the order they were defined, then 3) symbol properties in the order they were defined. Thus IF the JSON.stringify implementation follows this, equal objects (in the === sense but NOT NECESSARILY in the == sense) will stringify to equal values. More research needed. So I guess you could make an evil clone of an object with properties in the reverse order, but I cannot imagine it ever happening by accident...] At least on Chrome, the JSON.stringify function tends to return keys in the order they were defined (at least that I've noticed), but this behavior is very much subject to change at any point and should not be relied upon.If you choose not to use objects in your lists, this should work fine. If you do have objects in your list that all have a unique id, you can do a1.map(function(x)}{return {id:x.uniqueId}}). If you have arbitrary objects in your list, you can read on for option #2.)

如果您的数组包含对象,这可能不起作用。这是否仍然适用于对象取决于 JSON 实现是否对键进行排序。例如, 的 JSON{1:2,3:4}可能等于也可能不等于{3:4,1:2}; 这取决于实现,规范不做任何保证。[2017 年更新:实际上,ES6 规范现在保证对象键将按照 1) 整数属性,2) 属性按定义顺序迭代,然后 3) 符号属性按定义顺序迭代。因此,如果 JSON.stringify 实现遵循这一点,则相等的对象(在 === 意义上但不一定在 == 意义上)将字符串化为相等的值。需要更多的研究。所以我猜你可以用相反的顺序对一个具有属性的对象进行邪恶的克隆,但我无法想象它会偶然发生......]至少在 Chrome 上,JSON.stringify 函数倾向于按照定义的顺序返回键(至少我已经注意到),但这种行为在任何时候都可能发生变化,不应依赖。如果您选择不在列表中使用对象,这应该可以正常工作。如果您的列表中确实有对象都具有唯一 id,则可以执行a1.map(function(x)}{return {id:x.uniqueId}}). 如果您的列表中有任意对象,您可以继续阅读选项 #2。)

This works for nested arrays as well.

这也适用于嵌套数组。

It is, however, slightly inefficient because of the overhead of creating these strings and garbage-collecting them.

然而,由于创建这些字符串和对其进行垃圾收集的开销,它的效率略低。



Option 2

选项 2

More "proper" option, which you can override to deal with special cases (like regular objects and null/undefined and custom objects, if you so desire):

更多“正确”选项,您可以覆盖它以处理特殊情况(如常规对象和空/未定义和自定义对象,如果您愿意):

// generally useful functions
function type(x) { // does not work in general, but works on JSONable objects we care about... modify as you see fit
    // e.g.  type(/asdf/g) --> "[object RegExp]"
    return Object.prototype.toString.call(x);
}
function zip(arrays) {
    // e.g. zip([[1,2,3],[4,5,6]]) --> [[1,4],[2,5],[3,6]]
    return arrays[0].map(function(_,i){
        return arrays.map(function(array){return array[i]})
    });
}

 

 

// helper functions
function allCompareEqual(array) {
    // e.g.  allCompareEqual([2,2,2,2]) --> true
    // does not work with nested arrays or objects
    return array.every(function(x){return x==array[0]});
}

function isArray(x){ return type(x)==type([]) }
function getLength(x){ return x.length }
function allTrue(array){ return array.reduce(function(a,b){return a&&b},true) }
    // e.g. allTrue([true,true,true,true]) --> true
    // or just array.every(function(x){return x});

 

 

function allDeepEqual(things) {
    // works with nested arrays
    if( things.every(isArray) )
        return allCompareEqual(things.map(getLength))     // all arrays of same length
               && allTrue(zip(things).map(allDeepEqual)); // elements recursively equal

    //else if( this.every(isObject) )
    //  return {all have exactly same keys, and for 
    //          each key k, allDeepEqual([o1[k],o2[k],...])}
    //  e.g. ... && allTrue(objectZip(objects).map(allDeepEqual)) 

    //else if( ... )
    //  extend some more

    else
        return allCompareEqual(things);
}

Demo:

演示:

allDeepEqual([ [], [], [] ])
true
allDeepEqual([ [1], [1], [1] ])
true
allDeepEqual([ [1,2], [1,2] ])
true
allDeepEqual([ [[1,2],[3]], [[1,2],[3]] ])
true

allDeepEqual([ [1,2,3], [1,2,3,4] ])
false
allDeepEqual([ [[1,2],[3]], [[1,2],[],3] ])
false
allDeepEqual([ [[1,2],[3]], [[1],[2,3]] ])
false
allDeepEqual([ [[1,2],3], [1,[2,3]] ])
false

To use this like a regular function, do:

要像常规函数一样使用它,请执行以下操作:

function allDeepEqual2() {
    return allDeepEqual([].slice.call(arguments));
}

Demo:

演示:

allDeepEqual2([[1,2],3], [[1,2],3])
true


Options 3

选项 3

edit: It's 2016 and my previous overcomplicated answer was bugging me. This recursive, imperative "recursive programming 101" implementation keeps the code really simple, and furthermore fails at the earliest possible point (giving us efficiency). It also doesn't generate superfluous ephemeral datastructures (not that there's anything wrong with functional programming in general, but just keeping it clean here).

编辑:现在是 2016 年,我之前过于复杂的答案让我烦恼。这种递归的、命令式的“递归编程 101”实现使代码非常简单,而且在尽可能早的点上失败(提高了我们的效率)。它也不会生成多余的临时数据结构(并不是说函数式编程一般有什么问题,只是在这里保持干净)。

If we wanted to apply this to a non-empty arrays of arrays, we could do seriesOfArrays.reduce(arraysEqual).

如果我们想将其应用于非空数组,我们可以执行 seriesOfArrays.reduce(arraysEqual)。

This is its own function, as opposed to using Object.defineProperties to attach to Array.prototype, since that would fail with a key error if we passed in an undefined value (that is however a fine design decision if you want to do so).

这是它自己的函数,而不是使用 Object.defineProperties 附加到 Array.prototype,因为如果我们传入一个未定义的值,它会因关键错误而失败(如果你想这样做,这是一个很好的设计决定) .

This only answers OPs original question.

这仅回答 OP 的原始问题。

function arraysEqual(a,b) {
    /*
        Array-aware equality checker:
        Returns whether arguments a and b are == to each other;
        however if they are equal-lengthed arrays, returns whether their 
        elements are pairwise == to each other recursively under this
        definition.
    */
    if (a instanceof Array && b instanceof Array) {
        if (a.length!=b.length)  // assert same length
            return false;
        for(var i=0; i<a.length; i++)  // assert each element equal
            if (!arraysEqual(a[i],b[i]))
                return false;
        return true;
    } else {
        return a==b;  // if not both arrays, should be the same
    }
}

Examples:

例子:

arraysEqual([[1,2],3], [[1,2],3])
true
arraysEqual([1,2,3], [1,2,3,4])
false
arraysEqual([[1,2],[3]], [[1,2],[],3])
false
arraysEqual([[1,2],[3]], [[1],[2,3]])
false
arraysEqual([[1,2],3], undefined)
false
arraysEqual(undefined, undefined)
true
arraysEqual(1, 2)
false
arraysEqual(null, null)
true
arraysEqual(1, 1)
true
arraysEqual([], 1)
false
arraysEqual([], undefined)
false
arraysEqual([], [])
true

If you wanted to apply this to JSON-like data structures with js Objects, you could do so. Fortunately we're guaranteed that all objects keys are unique, so iterate over the objects OwnProperties and sort them by key, then assert that both the sorted key-array is equal and the value-array are equal, and just recurse. We can extend this to include Maps as well (where the keys are also unique). (However if we extend this to Sets, we run into the tree isomorphism problem http://logic.pdmi.ras.ru/~smal/files/smal_jass08_slides.pdf- fortunately it's not as hard as general graph isomorphism; there is in fact an O(#vertices) algorithm to solve it, but it can get very complicated to do it efficiently. The pathological case is if you have a set made up of lots of seemingly-indistinguishable objects, but upon further inspection some of those objects may differ as you delve deeper into them. You can also work around this by using hashing to reject almost all cases.)

如果您想将其应用于带有 js 对象的类 JSON 数据结构,您可以这样做。幸运的是,我们保证所有对象的键都是唯一的,因此迭代对象 OwnProperties 并按键对它们进行排序,然后断言排序的键数组和值数组相等,然后递归。我们可以将其扩展为也包括 Maps(其中的键也是唯一的)。(但是,如果我们将此扩展到 Sets,我们会遇到树同构问题http://logic.pdmi.ras.ru/~smal/files/smal_jass08_slides.pdf- 幸运的是它不像一般的图同构那么难;实际上有一个 O(#vertices) 算法来解决它,但是要高效地完成它会变得非常复杂。病态的情况是,如果您有一个由许多看似无法区分的对象组成的集合,但经过进一步检查,其中一些对象可能会随着您深入研究而有所不同。您还可以通过使用散列来拒绝几乎所有情况来解决此问题。)



Option 4: (continuation of 2016 edit)

选项 4:(2016 年编辑的延续)

This should work with most objects:

这应该适用于大多数对象:

function deepEquals(a,b) {
    if (a instanceof Array && b instanceof Array)
        return arraysEqual(a,b);
    if (Object.getPrototypeOf(a)===Object.prototype && Object.getPrototypeOf(b)===Object.prototype)
        return objectsEqual(a,b);
    if (a instanceof Map && b instanceof Map)
        return mapsEqual(a,b);        
    if (a instanceof Set && b instanceof Set)
        throw "Error: set equality by hashing not implemented."
    if ((a instanceof ArrayBuffer || ArrayBuffer.isView(a)) && (b instanceof ArrayBuffer || ArrayBuffer.isView(b)))
        return typedArraysEqual(a,b);
    return a==b;  // see note[1] -- IMPORTANT
}

function arraysEqual(a,b) {
    if (a.length!=b.length)
        return false;
    for(var i=0; i<a.length; i++)
        if (!deepEquals(a[i],b[i]))
            return false;
    return true;
}
function objectsEqual(a,b) {
    var aKeys = Object.getOwnPropertyNames(a);
    var bKeys = Object.getOwnPropertyNames(b);
    if (aKeys.length!=bKeys.length)
        return false;
    aKeys.sort();
    bKeys.sort();
    for(var i=0; i<aKeys.length; i++)
        if (aKeys[i]!=bKeys[i]) // keys must be strings
            return false;
    return deepEquals(aKeys.map(k=>a[k]), aKeys.map(k=>b[k]));
}
function mapsEqual(a,b) {
    if (a.size!=b.size)
        return false;
    var aPairs = Array.from(a);
    var bPairs = Array.from(b);
    aPairs.sort((x,y) => x[0]<y[0]);
    bPairs.sort((x,y) => x[0]<y[0]);
    for(var i=0; i<a.length; i++)
        if (!deepEquals(aPairs[i][0],bPairs[i][0]) || !deepEquals(aPairs[i][1],bPairs[i][1]))
            return false;
    return true;
}
function typedArraysEqual(a,b) {
    a = new Uint8Array(a);
    b = new Uint8Array(b);
    if (a.length != b.length)
        return false;
    for(var i=0; i<a.length; i++)
        if (a[i]!=b[i])
            return false;
    return true;
}

Demo (not extensively tested):

演示(未经广泛测试):

var nineTen = new Float32Array(2);
nineTen[0]=9; nineTen[1]=10;
deepEquals(
    [[1,[2,3]], 4, {a:5,b:6}, new Map([['c',7],['d',8]]), nineTen],
    [[1,[2,3]], 4, {b:6,a:5}, new Map([['d',8],['c',7]]), nineTen]
)

(sidenote: Maps are es6 dictionaries. I can't tell if they have O(1) or O(log(N)) lookup performance, but in any case they are 'ordered' in the sense that they keep track of the order in which key-value pairs were inserted into them. However, the semantic of whether two Maps should be equal if elements were inserted in a different order into them is ambiguous. I give a sample implementation below of a deepEquals that considers two maps equal even if elements were inserted into them in a different order.)

(旁注:地图是 es6 字典。我不知道它们是否具有 O(1) 或 O(log(N)) 查找性能,但无论如何它们都是“有序”的,因为它们会跟踪顺序其中插入了键值对。但是,如果元素以不同的顺序插入其中,则两个 Map 是否应该相等的语义是不明确的。我在下面给出了一个 deepEquals 的示例实现,它认为两个映射甚至相等如果元素以不同的顺序插入其中。)

(note [1]: IMPORTANT: NOTION OF EQUALITY: You may want to override the noted line with a custom notion of equality, which you'll also have to change in the other functions anywhere it appears. For example, do you or don't you want NaN==NaN? By default this is not the case. There are even more weird things like 0=='0'. Do you consider two objects to be the same if and only if they are the same object in memory? See https://stackoverflow.com/a/5447170/711085. You should document the notion of equality you use. )

(注意 [1]:重要:等式概念:您可能希望使用自定义的等式概念来覆盖注释行,您还必须在其他函数出现的任何位置更改该概念。例如,您是还是不? '不是你想要 NaN==NaN 吗?默认情况下不是这样。还有更奇怪的东西,比如 0=='0'。你认为两个对象是相同的,当且仅当它们在内存?请参阅https://stackoverflow.com/a/5447170/711085。您应该记录您使用的平等概念。)

You should be able to extend the above to WeakMaps, WeakSets. Not sure if it makes sense to extend to DataViews. Should also be able to extend to RegExps probably, etc.

您应该能够将上述内容扩展到 WeakMaps、WeakSets。不确定扩展到 DataViews 是否有意义。也应该能够扩展到 RegExps 等。

As you extend it, you realize you do lots of unnecessary comparisons. This is where the typefunction that I defined way earlier (solution #2) can come in handy; then you can dispatch instantly. Whether that is worth the overhead of (possibly? not sure how it works under the hood) string representing the type is up to you. You can just then rewrite the dispatcher, i.e. the function deepEquals, to be something like:

当你扩展它时,你意识到你做了很多不必要的比较。这是type我之前定义的函数(解决方案#2)可以派上用场的地方;然后你可以立即发货。这是否值得(可能?不确定它在引擎盖下是如何工作的)表示类型的字符串的开销取决于您。然后您可以将调度程序(即 function )重写为deepEquals如下所示:

var dispatchTypeEquals = {
    number: function(a,b) {...a==b...},
    array: function(a,b) {...deepEquals(x,y)...},
    ...
}
function deepEquals(a,b) {
    var typeA = extractType(a);
    var typeB = extractType(a);
    return typeA==typeB && dispatchTypeEquals[typeA](a,b);
}

回答by machineghost

jQuery does not have a method for comparing arrays. However the Underscore library(or the comparable Lodash library) does have such a method: isEqual, and it can handle a variety of other cases (like object literals) as well. To stick to the provided example:

jQuery 没有比较数组的方法。然而,Underscore(或类似的 Lodash 库)确实有这样一个方法:isEqual,它也可以处理各种其他情况(如对象文字)。坚持提供的例子:

var a=[1,2,3];
var b=[3,2,1];
var c=new Array(1,2,3);

alert(_.isEqual(a, b) + "|" + _.isEqual(b, c));

By the way: Underscore has lots of other methods that jQuery is missing as well, so it's a great complement to jQuery.

顺便说一句:Underscore 有很多其他 jQuery 也没有的方法,所以它是对 jQuery 的一个很好的补充。

EDIT:As has been pointed out in the comments, the above now only works if both arrays have their elements in the same order, ie.:

编辑:正如评论中指出的那样,上面的内容现在仅在两个数组的元素顺序相同时才有效,即:

_.isEqual([1,2,3], [1,2,3]); // true
_.isEqual([1,2,3], [3,2,1]); // false

Fortunately Javascript has a built in method for for solving this exact problem, sort:

幸运的是 Javascript 有一个内置的方法来解决这个确切的问题,sort

_.isEqual([1,2,3].sort(), [3,2,1].sort()); // true

回答by soheildb

For primitive values like numbers and strings this is an easy solution:

对于像数字和字符串这样的原始值,这是一个简单的解决方案:

a = [1,2,3]

b = [3,2,1]

a.sort().toString() == b.sort().toString() 

The call to sort()will ensure that the order of the elements does not matter. The toString()call will create a string with the values comma separated so both strings can be tested for equality.

调用sort()will 确保元素的顺序无关紧要。该toString()调用将创建一个字符串,其中的值以逗号分隔,因此可以测试两个字符串的相等性。

回答by rplantiko

With JavaScript version 1.6 it's as easy as this:

使用 JavaScript 1.6 版就这么简单:

Array.prototype.equals = function( array ) {
  return this.length == array.length && 
         this.every( function(this_i,i) { return this_i == array[i] } )  
  }

For example, [].equals([])gives true, while [1,2,3].equals( [1,3,2] )yields false.

例如,[].equals([])给出true,而[1,2,3].equals( [1,3,2] )产生false

回答by claudiut

Even if this would seem super simple, sometimes it's really useful. If all you need is to see if two arrays have the same items and they are in the same order, try this:

即使这看起来非常简单,但有时它确实很有用。如果您只需要查看两个数组是否具有相同的项并且它们的顺序是否相同,请尝试以下操作:

[1, 2, 3].toString() == [1, 2, 3].toString()
true
[1, 2, 3,].toString() == [1, 2, 3].toString()
true
[1,2,3].toString() == [1, 2, 3].toString()
true

However, this doesn't work for mode advanced cases such as:

但是,这不适用于模式高级情况,例如:

[[1,2],[3]].toString() == [[1],[2,3]].toString()
true

It depends what you need.

这取决于你需要什么。

回答by stantont

Based on Tim James answerand Fox32's comment, the following should check for nulls, with the assumption that two nulls are not equal.

根据 Tim James 的回答和 Fox32 的评论,以下内容应检查空值,并假设两个空值不相等。

function arrays_equal(a,b) { return !!a && !!b && !(a<b || b<a); }

> arrays_equal([1,2,3], [1,3,4])
false
> arrays_equal([1,2,3], [1,2,3])
true
> arrays_equal([1,3,4], [1,2,3])
false
> arrays_equal(null, [1,2,3])
false
> arrays_equal(null, null)
false

回答by uKolka

jQuery has such method for deep recursive comparison.

jQuery 有这种深度递归比较的方法。

A homegrown general purpose strict equalitycheck could look as follows:

本土通用的严格平等检查可能如下所示:

function deepEquals(obj1, obj2, parents1, parents2) {
    "use strict";
    var i;
    // compare null and undefined
    if (obj1 === undefined || obj2 === undefined || 
        obj1 === null || obj2 === null) {
        return obj1 === obj2;
    }

    // compare primitives
    if (typeof (obj1) !== 'object' || typeof (obj2) !== 'object') {
        return obj1.valueOf() === obj2.valueOf();
    }

    // if objects are of different types or lengths they can't be equal
    if (obj1.constructor !== obj2.constructor || (obj1.length !== undefined && obj1.length !== obj2.length)) {
        return false;
    }

    // iterate the objects
    for (i in obj1) {
        // build the parents list for object on the left (obj1)
        if (parents1 === undefined) parents1 = [];
        if (obj1.constructor === Object) parents1.push(obj1);
        // build the parents list for object on the right (obj2)
        if (parents2 === undefined) parents2 = [];
        if (obj2.constructor === Object) parents2.push(obj2);
        // walk through object properties
        if (obj1.propertyIsEnumerable(i)) {
            if (obj2.propertyIsEnumerable(i)) {
                // if object at i was met while going down here
                // it's a self reference
                if ((obj1[i].constructor === Object && parents1.indexOf(obj1[i]) >= 0) || (obj2[i].constructor === Object && parents2.indexOf(obj2[i]) >= 0)) {
                    if (obj1[i] !== obj2[i]) {
                        return false;
                    }
                    continue;
                }
                // it's not a self reference so we are here
                if (!deepEquals(obj1[i], obj2[i], parents1, parents2)) {
                    return false;
                }
            } else {
                // obj2[i] does not exist
                return false;
            }
        }
    }
    return true;
};

Tests:

测试:

// message is displayed on failure
// clean console === all tests passed
function assertTrue(cond, msg) {
    if (!cond) {
        console.log(msg);
    }
}

var a = 'sdf',
    b = 'sdf';
assertTrue(deepEquals(b, a), 'Strings are equal.');
b = 'dfs';
assertTrue(!deepEquals(b, a), 'Strings are not equal.');
a = 9;
b = 9;
assertTrue(deepEquals(b, a), 'Numbers are equal.');
b = 3;
assertTrue(!deepEquals(b, a), 'Numbers are not equal.');
a = false;
b = false;
assertTrue(deepEquals(b, a), 'Booleans are equal.');
b = true;
assertTrue(!deepEquals(b, a), 'Booleans are not equal.');
a = null;
assertTrue(!deepEquals(b, a), 'Boolean is not equal to null.');
a = function () {
    return true;
};
assertTrue(deepEquals(
[
    [1, 1, 1],
    [2, 'asdf', [1, a]],
    [3, {
        'a': 1.0
    },
    true]
], 
[
    [1, 1, 1],
    [2, 'asdf', [1, a]],
    [3, {
        'a': 1.0
    },
    true]
]), 'Arrays are equal.');
assertTrue(!deepEquals(
[
    [1, 1, 1],
    [2, 'asdf', [1, a]],
    [3, {
        'a': 1.0
    },
    true]
],
[
    [1, 1, 1],
    [2, 'asdf', [1, a]],
    [3, {
        'a': '1'
    },
    true]
]), 'Arrays are not equal.');
a = {
    prop: 'val'
};
a.self = a;
b = {
    prop: 'val'
};
b.self = a;
assertTrue(deepEquals(b, a), 'Immediate self referencing objects are equal.');
a.prop = 'shmal';
assertTrue(!deepEquals(b, a), 'Immediate self referencing objects are not equal.');
a = {
    prop: 'val',
    inside: {}
};
a.inside.self = a;
b = {
    prop: 'val',
    inside: {}
};
b.inside.self = a;
assertTrue(deepEquals(b, a), 'Deep self referencing objects are equal.');
b.inside.self = b;
assertTrue(!deepEquals(b, a), 'Deep self referencing objects are not equeal. Not the same instance.');
b.inside.self = {foo: 'bar'};
assertTrue(!deepEquals(b, a), 'Deep self referencing objects are not equal. Completely different object.');
a = {};
b = {};
a.self = a;
b.self = {};
assertTrue(!deepEquals(b, a), 'Empty object and self reference of an empty object.');

回答by DOCTYPE HTML

Check every each value by a for loop once you checked the size of the array.

检查数组的大小后,通过 for 循环检查每个值。

function equalArray(a, b) {
    if (a.length === b.length) {
        for (var i = 0; i < a.length; i++) {
            if (a[i] !== b[i]) {
                return false;
            }
        }
        return true;
    } else {
        return false;
    }
}

回答by Chase Sandmann

If you are using lodash and don't want to modify either array, you can use the function _.xor(). It compares the two arrays as sets and returns the set that contains their difference. If the length of this difference is zero, the two arrays are essentially equal:

如果您正在使用 lodash 并且不想修改任何一个数组,您可以使用函数 _.xor()。它将两个数组作为集合进行比较,并返回包含它们差异的集合。如果该差值的长度为零,则两个数组本质上相等:

var a = [1, 2, 3];
var b = [3, 2, 1];
var c = new Array(1, 2, 3);
_.xor(a, b).length === 0
true
_.xor(b, c).length === 0
true