开发者

Is it possible to initialize multiple Javascript arrays in a loop?

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 :)


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 :)


You can achieve something like that using

  • JavaScript Two Dimensional Arrays
  • Building a MultiDimensional Array in Javascript
  • JavaScript Multi-Dimensional Arrays
  • JavaScript: Multi-dimensional Array


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] = [];
}


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.


You can just use a two dimensional array.


Example to initialize 10 empty arrays:

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜