I have a piece of code that checks the equality of arrays. It works like a charm when using it, like:
[1, 2, 3].equals([1, 2, 3]);
[1, 2, 3].equals([1, 2, 4]);
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 reason for this? I check if it has a property before using it ( if (this[i].equals)), so why does it say that? It is also true that undefined === undefined, therefore, I do not see what the problem is.
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;
}
source
share