0

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?

1
  • Can you show the code that populates the array? Commented Oct 21, 2013 at 7:34

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

tables.length is 0 since it's an associative array. tables.forEach doesn't work either.
@user2558051 then you shouldn't use an array at all. See eggward's answer.
0

Your declaration for tables should be:

var tables = {};

2 Comments

It looks like OP should use an object as map instead of an array, indeed. If you explain it a little, you'll have my +1.
Because what you want to do is associate t.attr('id') to your t object. Arrays do not behave like that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.