Nurvos | Speak

How not to build a dynamic array in JavaScript

Let’s say you wanted to build a dynamic array in JavaScript, using data retrieved from a J2EE servlet. How would you do it?

In my case, the data I was dealing with was in the following format: “variable=12345,23456,34567,45678″. I thought to myself, why don’t you just use the eval statement an dynamically write out the array:

Code (javascript)
  1. eval("var existingArray=new Array("+variable+")");

Looks great right? Do you see the bug? What about when “variable” only contains one element? Ah ha, instead of filling an array with X number of entries, it actually initializes with x number of indexes. In one of my cases, 400k items.

The solution ended up checked to see if the was one element in my “variable” and adjusting accordingly:

Code (javascript)
  1. if(variable.indexOf(‘,’) > 0){
  2. eval("var existingArray=new Array("+variable+")");
  3. }else{
  4. var existingArray = new Array(1);       existingArray[0]=variable
  5. }

Both IE and Firefox don’t like dealing with arrays 400k positions in size. Go figure.

Leave a Reply




XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>