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
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745628512a4636958.html
评论列表(0条)