View Full Version : initiating a variable number of arrays

11-08-2006, 08:28 PM

I am trying to initiate a variable number of arrays. I recently discovered the eval() function thanks to VortexCortex (althought he stated that he did not recommend using it).

Well I currently have the code to initiate my arrays such that...

var myArray0 = new Array();
var myArray1 = new Array();
var myArray2 = new Array();
var myArray3 = new Array();

As you can see, the number of arrays is predefined within the code however I am trying to initiate loop to initiate a variable number of arrays based on user input. Since my array names contain incrementing numbers on the ends of their names I thought to use the eval function to add the correct number onto the names like so...

var userInput = prompt("How many arrays would you like?");
for(i=0; i<=userInput; i++){
eval('var myArray' + i + ' = new Array()');

Is there something wrong with what I am doing with the eval function?

11-08-2006, 08:49 PM
hehe never mind. I realised that the whole line must be inside the eval() function.

11-08-2006, 08:57 PM
Minor thing but the user will get one more array than they asked for with that loop. To get the number they entered you'd need:

for (i=0; i < userInput; i++) {


for (i = 1; i <= userInput; i++) {

Might not matter to your code but I thought I'd point it out anyway.


11-08-2006, 10:29 PM
thanks for pointing that out although I have already accounted for it :)

11-08-2006, 10:57 PM
there is an easy solution to it.

instead of trying to create a variable amout of variables....
create an array whose value are arrays them self.

MyArray=new Array();
ITslength= // im asumming you want to create the arrays depending on a specified number, if so grab that number and put it here
myArray[i][0]=//first value of array
myArray[i][1]=//second value of array
myArray[i][2]=//third value of array
// and so on depending on how many values you want in your sub arrays

the to access them just call to the main array
the first sub array would be MyArray[0]
the second one would be MyArray[1]
.... and so on

hope this is what you are looking for in a way.