JavaScript

Not all arrays are arrays

You modified the Array object to include some of your custom methods. You create an array, you use the method and get an error:

Array.prototype.loop = function (fn) {
    var length = this.length;
    for (var i=0;i<length;i++){
        var item = this[i]; // item will refer to the current element
        fn.apply(item,[i]); // apply takes item as the context variable, and i as the argument for the index
    }
}

var allElements = document.getElementsByTagName("*");
allElements.loop(function() {
    // process each element
});

TypeError: undefined is not a function

The error means, loop is not defined. Let's try to debug it. allElements has the length property and can be accessed like an array.

var i, length = allElements.length;
for (i=0;i<length;i++){
    console.log(allElements[i].nodeName);
}

This method works just fine. Even though this object behaves like an array, it is not an Array. It is an HTMLCollection.

typeof allElements; // object
allElements.constructor.name; // HTMLCollection

There is another object that behaves like an array but isn't. When a function is created, a special variable is connected to it, it holds all the arguments that were passed in an array like object.

function doSomething() {
    console.log(arguments)

}

doSomething(1,2,3,4,5);

// prints [1,2,3,4,5]

Just like the HTMLCollection, this is a special object that behaves like an array but isn't. If we perform the same tests as before, this is what we get.

function doSomething() {
    typeof arguments; // object
    arguments.constructor.name; // Object
}

doSomething(1,2,3,4,5);

This is probably a generic object created from the Object object.

In summary, not everything that behaves like an array is an array. One way to make sure is to test the object first in the manner described here.


Comments

There are no comments added yet.

Let's hear your thoughts

For my eyes only