最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - For-in with a hard-coded array - Stack Overflow

matteradmin4PV0评论

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!

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!

Share Improve this question asked Aug 17, 2012 at 22:23 Lee GreyLee Grey 3231 gold badge5 silver badges16 bronze badges 3
  • 3 What is the i in all[i][p]? – Vlad Commented Aug 17, 2012 at 22:25
  • From a debugging and readability standpoint making the array a variable is preferable to an anonymous array. – scrappedcola Commented Aug 17, 2012 at 22:28
  • Sorry about the confusion. Yeah, I'm iterating over the DOM, so all=document.getElementsByTagName("*"). – Lee Grey Commented Aug 17, 2012 at 23:25
Add a ment  | 

1 Answer 1

Reset to default 6

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
});
Post a comment

comment list (0)

  1. No comments so far