简体   繁体   中英

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?

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.

您对表格的声明应为:

var tables = {};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM