5

Let's say i have a for loop and i want to initialize multiple arrays in that loop. Can it be achieved like this?:

for (var i = 0; i < 5; i++){
  var array+i = [];
}

So that the arrays that will be created are array0,array1,array2,array3,array4?

Any help would be much appreciated :)

7 Answers 7

4

You can use a multi dimensional array to tackle this problem:

for(var i=0;i<5;i++){
  var array[i]=[];
}

which will result in:

array[0] = []
array[1] = []
array[2] = []
array[3] = []
array[4] = []

hope that helps :)

Sign up to request clarification or add additional context in comments.

Comments

1

You can achieve something like that using

Comments

1

You can create an array of arrays:

var arr = [];
for (var i = 0; i < 5; i++) {
    arr[i] = [];
}

Or if it must be a global variable (probably not a good idea):

for (var i = 0; i < 5; i++) {
    window["array" + i] = [];
}

Comments

1

You could probably eval it out,

for (var i=0;i<5;i++) {
 eval("var array"+i+"=[];");
}

But eval is evil, it would make much more sense to just use a 2 dimensional array.

Comments

0

You can just use a two dimensional array.

Comments

0

Example to initialize 10 empty arrays:

let subArrays = Array.from({length: 10}, () => []);

Comments

-1

If you're in a browser and willing to do something hacky you can use the top-level object, namely window:

for (var i = 0; i < 5; i++) {
  window["array" + i] = [];
}

After doing this, you'll be able to refer to each array as array1 or whichever number you want.

This said, you should probably never actually use this method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.