开发者

How do I compare two arrays (which can have: DOM elements, numbers, strings, arrays or dictionaries) using jQuery?

I found this method:

Array.prototype.compare = function(arr) {
    if (this.length != arr.length) return false;
    for (var i = 0; i < arr.length; i++) {
        if (this[i].compare) {
            if (!this[i].compare(arr[i])) return false;
        }
        if (this[i] !== arr[i]) return false;
    }
    return tru开发者_开发知识库e;
}


var a = ['aa',[1,2,3]]
var b = ['aa',[1,2,3]]
alert(a.compare (b))

.

But, when I make a deep compare, it returns false.

So what method do you use to compare two arrays, using jquery?

Thanks


There's no jQuery solution for this - jQuery is mainly used for DOM manipulation, ajax and some simple animations. It does come with a small collection of utilities, but as far as I know none of them have this function.

I did, however, find the bug in your code.

Array.prototype.compare = function(arr) {
    if (this.length != arr.length) return false;
    for (var i = 0; i < arr.length; i++) {
        if (this[i].compare) {
            if (!this[i].compare(arr[i])) return false;
        } else { // <-- Here!
            if (this[i] !== arr[i]) return false;
        }
    }
    return true;
}

You need to use if - else here, instead of running both the .compare function again and comparing them with the equality operator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜