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 returnsfalse
.
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.
精彩评论