-1

I have need to create arrays dynamically using JavaScript/JQuery. What I did is as follows:

var count = 5;
for(var j=0;j<count;j++){
        var arrayname = "array"+j;
        var arrayname  = [];    
    }

After creation I am expecting arrays array0[],array1[],array2[],array3[],array4[]

So I printed as

alert(array0);

But I am getting error as follows:

Uncaught ReferenceError: array0 is not defined

It occurred because array0[] is not global its bound is only inside that for loop. How can I create dynamic array so that all the arrays can be accessed from outside also?

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
Santhucool
  • 1,656
  • 2
  • 36
  • 92
  • 1
    Why not use a single variable? An array in JavaScript can hold additional arrays within it, creating a structure similar to a multi-dimensional array – `var array = []; for (var j = 0; j < count; j++) array.push([]);`. With that, `array0[1]` would instead be `array[0][1]`. – Jonathan Lonowski Nov 18 '15 at 06:58

1 Answers1

2

You can use eval() to define variable dynamically

var count = 5;
for (var j = 0; j < count; j++) {
  eval('var array' + j + '=[]');
}

console.log(array0);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188