...

View Full Version : initiating a variable number of arrays



aatwo
11-08-2006, 07:28 PM
Hi.

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?");
parseInt(userInput);
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?

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

david_kw
11-08-2006, 07: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++) {

or

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

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

david_kw

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

brandonH
11-08-2006, 09: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();
i='0';
ITslength= // im asumming you want to create the arrays depending on a specified number, if so grab that number and put it here
while(i<ITslength){
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.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum