Reputation: 1095
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
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