Array equality check algorithm does not work in certain cases

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]); // 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 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;
}
+3
source share
1 answer

This line:

    if (this[i].equals) {

it should be:

    if (this[i] && this[i].equals) {

so if this[i]there is undefined, you will not try to access the property on undefined.


: , , Array, , .equals.

:

if( Object.prototype.toString.call( this[i] ) === '[object Array]' ) {

, , new, typeof.

+2

Source: https://habr.com/ru/post/1791678/


All Articles