I have a piece of code which checks for equality of arrays. It works like a charm when using it like:
[1, 2, 3].equals([1, 2, 3]); // true
[1, 2, 3].equals([1, 2, 4]); // false
The above result is obvious and correct, of course. However, the following case fails:
[1, 2, undefined].equals([1, 2, undefined]);
// Error: Cannot read property 'equals' of undefined
What could be the cause of it? I check whether it has the property before using it (if (this[i].equals)
), so why does it say this? It is also true that undefined === undefined
, so I do not see what's the problem.
The function:
Array.prototype.equals = function(arr) {
if (this.length !== arr.length) {
return false;
}
for (var i = 0; i < arr.length; i++) {
if (this[i].equals) {
if (!this[i].equals(arr[i])) {
return false;
} else {
continue;
}
}
if (this[i] !== arr[i]) {
return false;
}
}
return true;
}
if (this==arr) return true;
to the top of your test for a fast out when the same object is passed as an argument; b) you should cache the length of your array for speed,for (var i=0,len=arr.length;i<len;++i){ .. }