JavaScript Array Iteration Madness
A few days ago I ran across a situation that was making me pull my hair out for half an afternoon. I was simply trying to iterate a JavaScript array to display some validation error messages that came back from the server as JSON. Easy, I thought, should be able to knock that out in about 2.2 seconds. Of course we know that isn’t true or I would have to change the name of the blog to The Good Programmer.
Take a look at this simple JavaScript:
The output of this code should be the browser displaying an alert box with “foo bar something” in it right? Well that is what I thought, but no, the alert box has “0 1 2” on it. Don’t believe me? Try it for yourself.
Obviously, what is being shown is the array index and not the value at the index. Running this code through the Safari’s excellent Web Inspector and its script debugger clearly shows errors is an Array and not some other data structure I would have to reference further to get to my values.
The solution is to of course use a standard indexed for loop, like so:
Then the output is what you expect.
So the obvious question is why does the for-in loop show the array indices and not the values? If you were expecting an answer then you obviously didn’t read the title of this blog. I don’t have a fscking clue.