Explicat
Explicat

Reputation: 1095

Prototype object when looping through array?

I'm getting confusing results when looping through an array.

Filling the array looks like

var tables = [];
// ...
// t is table as jQuery object
tables[t.attr('id')] = t;

Later, when looping through the tables array, I'm getting one more element than I've actually added. The program breakes when the other object reaches t.removeClass()

for (t in tables) {
    var t = tables[t];
    t.removeClass(...);
}

Visual Studio Debugger describes the other object as "clone", which is the first method of the prototype object/property(?).

tables
    [prototype]
        [Methods]
            clone
            ...
        [prototype]
    MyTable0
    MyTable1

I've read that every javascript object comes with a prototype property but why is prototype here treated as an object?

Upvotes: 0

Views: 64

Answers (2)

eggward
eggward

Reputation: 345

Your declaration for tables should be:

var tables = {};

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382150

Note : if your id aren't numbers, then you don't need an array, look at the other answer.

To loop over an array, don't use the for..in construct.

Use

for (var i=0; i<tables.length; i++) {
    var t = tables[i];
    t.removeClass(...);
}

or if you don't care for IE8 :

tables.forEach(function(t) {
    t.removeClass(...);
});

or with jQuery :

$.each(tables, function(_,t){
    t.removeClass(...);
});

Side note : it looks like somebody poorly enriched the prototype of the native Array class. It's generally seen as bad practice. Doing so and making the property enumerable is even worse. You should consider dropping or fixing the library you use.

Upvotes: 1

Related Questions