articles:

extra items in javascript array

I recently got an email asking why a div, whose content was a list dynamically generated from an javascript array, was suddenly displaying what appeared to be a load of random stuff in addition to the contents of the array. I had come across a similar problem before and therefore offered this response (the overlay method mentioned below is causes the div to be shown and the array to be iterated through at a set interval).

I am guessing that you are calling the overlay method on a page that includes a JavaScript framework of some description, if the framework uses prototyping then it messes up for loops by adding a bunch of additional properties to objects, therefore when you iterate through an array not only do you get the contents of the array (i.e. the strings in this case) you also get the additional properties that the prototyping has given the array object. My guess what you are seeing is the additional properties that the new prototype array has been given, in this case a set of functions. Aren't frameworks great.

One way of working around this, which normally works is to not use for...in loops for iterating through arrays, but switch to for (i=0;i<array.length;i++){.....}

Post a comment

name:
(optional)

email:
(optional)

comment: