最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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
});
发布评论

评论列表(0)

  1. 暂无评论