如何知道两个数组是否具有相同的值 [英] How to know if two arrays have the same values

查看:149
本文介绍了如何知道两个数组是否具有相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这两个数组:一个用ajax请求填充信息,另一个存储用户点击的按钮。我使用这个代码(我填充了样本数):

I have these two arrays: one is filled with information from an ajax request and another stores the buttons the user clicks on. I use this code (I filled with sample numbers):

var array1 = [2, 4];
var array2 = [4, 2]; //It cames from the user button clicks, so it might be disordered.
array1.sort(); //Sorts both Ajax and user info.
array2.sort();
if (array1==array2) {
    doSomething();
}else{
    doAnotherThing();
}

但它总是给出 false ,即使这两个数组相同,但使用不同的名称。 (我在Chrome的JS控制台中检查过这个)。所以,有没有任何方式,我可以知道如果这两个数组包含相同?为什么给它 false ?如何知道第一个数组中的哪些值不在第二个?

But it always gives false, even if the two arrays are the same, but with different name. (I checked this in Chrome's JS Console). So, is there any way I could know if these two arrays contain the same? Why is it giving false? How can I know which values in the first array are not in the second?

推荐答案

Array.prototype.compare = function(testArr) {
    if (this.length != testArr.length) return false;
    for (var i = 0; i < testArr.length; i++) {
        if (this[i].compare) { //To test values in nested arrays
            if (!this[i].compare(testArr[i])) return false;
        }
        else if (this[i] !== testArr[i]) return false;
    }
    return true;
}

var array1 = [2, 4];
var array2 = [4, 2];
if(array1.sort().compare(array2.sort())) {
    doSomething();
} else {
    doAnotherThing();
}

也许?

这篇关于如何知道两个数组是否具有相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆