PolandSpring PolandSpring - 1 year ago 100
Javascript Question

for ... in loop with string array outputs indices

When I write some javascript such as this:

var words = ['word1', 'word2', 'word3']

for (word in words) {

The resulting output is the numeric indices of the respective word. I did some searching on Google and I couldn't find the exact reason for this behavior. I'm guessing that this is completely expected behavior but I would like to know the reason why.


Answer Source

Why is nobody providing the correct answer? You NEVER iterate arrays with a for/in loop - that is only for iterating plain objects and their keys, not for iterating the items in an array.

You iterate arrays for a for loop like this:

var words = ['word1', 'word2', 'word3'];

for (var i = 0, len = words.length; i < len; i++) {
    // here words[i] is the array element

Or, in a modern browser, you can use the .forEach() method of arrays:

var words = ['word1', 'word2', 'word3'];

words.forEach(function(value, index, array) {
    // here value is the array element being iterated

See here at MDN for more info on .forEach().

ndp's reference to this post shows some good examples of things that can go wrong using for/in with arrays. You can make it works sometimes, but it is not the smart way to write Javascript array iteration.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download