Tag Archives: for loop

Looping over javascript arrays with Prototype framework

Had an array in javascript and tried to loop over it using

for (x in array){

...some code

}

I was confused why it seemed to have lots more members than I had put in with contents that seemed to be functions.  So I used console.log and firebug to print out the array members and saw that they were the methods you could call on an array object.

A quick google revealed that (see here)

using forin on arrays when using Prototype will enumerate all extended methods as well, such as those coming from the Enumerable module, and those Prototype puts in the Array namespace

and that the best (only?) way to do it in Prototype is

myArray.each(function(item) {

// Your code working on item here...

});

It’s all sorted now!