简体   繁体   中英

For-in with a hard-coded array

Rookie JS question here:

for( var p in ['nodeName', 'nodeType', 'tagName', 'localName'] ) {
    console.log( p + '=' + all[i][p] + '\n' );
}

I expected to see something like

nodeName=DIV

Instead, I get

0=undefined

Am I forced to assign the array to a variable, so that I can index into it? Is there a way to use this syntax in the for-in and retrieve the string from the array?

Thanks!

Using for..in for an array is almost always wrong . It iterates over object properties, not over values -s so in your case it yields you 0, 1, 2 and 3. It gets even worse if you decide to extend Array.prototype with custom methods (which, unlike extending Object.prototype is not a big no-go). Their names will also be iterated over when using for..in .

The proper way to do what you want is this:

var foo = [...];
for(var i = 0; i < foo.length; i++) {
    // use foo[i]
}

or this (in modern browsers or with the function being shim'd):

[...].forEach(function(value) {
    // use value
});

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