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 tru开发者_如何学JAVAe 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;
}
This line:
if (this[i].equals) {
should be:
if (this[i] && this[i].equals) {
so that if this[i]
is undefined
, you won't be trying to access a property on undefined
.
EDIT: Since you seem to be testing for an Array, it will be safer to do a more explicit test, since any Object could potentially have an .equals
property.
You may want to do this instead:
if( Object.prototype.toString.call( this[i] ) === '[object Array]' ) {
It's a bit longer, but will accurately detect an Array, even if it was created using the new
keyword, which would throw off the typeof
operator.
精彩评论