Tuesday, March 17, 2009

Prototype.js and for(..in..) loops

I had a problem a while ago where I was using a for(..in..) loop to go through a hash map (like an array but has strings for the index instead of numbers). Now you NEED a for(..in..) loop for these, because you don't always know what the indexes are going to be called, and you can't call them sequentially like a normal array. Problem was that I was getting back what looked like javascript functions instead of the values I expected, so I did what any programmer would do after finding no easy explanation - I just checked for that function keyword, the length of the string etc, and skipped over the values that were not in a format that would work. Since then I have encountered the problem again, but luckily it was on a site where the developer knew his stuff:

http://www.prototypejs.org/api/array

it seems that the prototype.js javascript library absolutely hates the for(..in..) loop. So for these site you have to return the array as an enumerable type and then use the each function. If you are writing code to go across multiple sites, you may want to use a try catch block to check the existence of each going forward.

You have now been warned

**Edit**

I stumbled upon this easy fix:

var object = new Object();
for(var key in object){
if(!(key in Object.prototype)){
// do some stuff SAFELY!
}
}

No comments: