JS: Looping through array (for ... in)
Why isit when I do
http://jsfiddle.net/xe4Ph/1/
var footnoteLinks = [1,2,3];
for (var i in footnoteLinks) {
document.write(footnoteLinks[i] + ", ");
}
What I get is something like ...
1, 2, 3, function () { return lower; }, function Array() { [native cod开发者_运维百科e] }, function pop() { [native code] }, function push() { [native code] }, function reverse() { [native code] }, function shift() { [native code] }, function sort() { [native code] }, function splice() { [native code] }, function unshift()
Why is that? Whats with the functions etc... I think it worked ok b4, I dunno what caused this now, it seems the same for all browsers I tried. Firefox 3.6, Chrome 6 (i think?), IE9
The for(var in obj)
is for iterating over the properties of an object. You're getting the properties of the Array object you've created.
You want a more traditional looping/index construct:
for(var i=0,z=footnoteLinks.length; i<z; i++)
Some JavaScript runtimes also have map
and reduce
methods on Array objects, but this isn't guaranteed. Most JavaScript libraries have something like this (or perhaps an each
method), though.
In javascript,
for (var k in {a:1, b:2}) {
doesn't just iterate over a and b; it also iterates over all of the members of the prototype of that object. Since functions are values in javascript, that includes all of the methods of Object. There are three ways to avoid this:
- Check that obj.hasOwnProperty(k) before you use k
- If you're iterating over an array, use the forEach method of array (or equivalent in your favorite javascript library)
- If you're iterating over an array, use the for(var i=0; i < obj.length; i++) construct (length counts only the elements of the array)
An alternative to Weston C's answer would be using the hasOwnProperty
function in the for in
loop, as suggested by Chris Morgan:
for(var i in obj) if(obj.hasOwnProperty(i)) {
document.write(obj[i]);
}
And yes, it is slower than iterating using the traditional for
loop.
The for/in
loop cannot be used to iterate over an array, since it also enumerates user-defined properties (see the MDC documentation). There’s a forEach
method on array objects and for each/in
loop, but only in JavaScript 1.6+ (= not much usable right now). You might want to use some of the many JavaScript frameworks or code your own utility function to iterate over arrays:
function iterate(a, func) {
for (var i=0; i<a.length; i++)
func(a[i]);
}
iterate([1, 2], function(x) { console.log(x) });
精彩评论