How not to build a dynamic array in JavaScript
November 8th, 2006
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:
-
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:
-
if(variable.indexOf(‘,’) > 0){
-
eval("var existingArray=new Array("+variable+")");
-
}else{
-
var existingArray = new Array(1); existingArray[0]=variable
-
}
Both IE and Firefox don’t like dealing with arrays 400k positions in size. Go figure.


Leave a Reply