Wednesday, September 10, 2008

A safer way to iterate over arrays in JavaScript

We'd had a piece of JavaScript that iterated over an array using the "for (var x in arr)" syntax working fine, until... we included json.js into the file. The trouble began... You see, json.js extends all arrays by tacking an extra key => value pair as the array's last element. The key is something like "toJSONString" and the value is a function which converts the object into a JSON-format string. Using the "for (var x in arr)" syntax to iterate over arrays still worked, but the code in the for loop was assuming that the value was a piece of text, not a function. Hence my code was crapping out. Thanks to FireBug (THANK YOU!) I determined the cause of the crap. The solution, however, was provided by this wonderful post, the take-away of which is: Use the "for (var x = 1; x < arr.length; x++)" syntax. It's safer. The End.