Search code examples
javascriptarraysgetelementsbytagname

Javascript for...in statement gives error when looping through array


I just tried the for...in statement in Javascript.

This gives no error:

var images = document.getElementsByTagName('img');

for(x in images){
    document.write(images[x]) + " ");
}

However, this does what it should but gives an error in the FF error console.

for(x in images){
    images[x].style.visibility="visible";
}

This made me VERY curious as to what's going on.

Doing this:

for(x in images){
    document.write(x);
}

...gave me this:

01234567891011121314151617lengthitemnamedItem

What's there at the end? I assume this makes the document.images / document.getElementsByTagName('img') array not suitable to use with the for...in statement since the values for x at the end won't correspond to an image? Maybe a for loop is better?


Solution

  • Don't iterate through arrays with for ... in loops. Use an index:

    for (var i = 0; i < arr.length; ++i) {
      // images[i] ...
    }
    

    The for ... in construct isn't wrong, it's just not what you want to do; it's for when you want to iterate through all properties of an object. Arrays are objects, and there are other properties besides the semantically-interesting indexed elements.

    (Actually what comes back from getElementsByTagName isn't really an Array; it's a node list. You can however treat it like an array and it'll generally work OK. The same basic caveat applies for for ... in in any case.)