views:

46

answers:

2

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 true;
}


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

A: 

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.

Yi Jiang
A: 
var a = ['aa',[1,2,3]]
var b = ['aa',[1,2,3]]
alert(a.sort().toString()==b.sort().toString())
zjm1126