admin管理员组文章数量:1434900
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
inall[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
1 Answer
Reset to default 6Using 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
});
本文标签: javascriptForin with a hardcoded arrayStack Overflow
版权声明:本文标题:javascript - For-in with a hard-coded array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745628511a2667123.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论