你能在Javascript中使用变量名中的变量吗? [重复]

时间:2021-09-11 00:10:40

This question already has an answer here:

这个问题在这里已有答案:

var array1  = new Array(4);
var array2  = new Array(4);
var array3  = new Array(4);
var array4  = new Array(4);
var array5  = new Array(4);
var array6  = new Array(4);
var array7  = new Array(4);

for(var a = 1; a < 8; a++){
    array+ a = new Array(4);
}

I want to make an array with a for loop, but the variables has to be diffrent every time. So my question if this is possible, and if it is, how?

我想用for循环创建一个数组,但变量必须每次都不同。所以我的问题是否可行,如果可能,怎么样?

2 个解决方案

#1


2  

No you can't (not unless you use Eval() which you shouldn't...).

不,你不能(除非你使用你不应该使用的Eval())。

As Justinas has commented, you could use a Multidimensional array.

正如Justinas所评论的那样,你可以使用多维数组。

var array = [];
array.push(new Array(4));
array.push(new Array(4));
array.push(new Array(4));
array.push(new Array(4));
array.push(new Array(4));
array.push(new Array(4));
array.push(new Array(4));

for(var a = 1; a < 8; a++){
    array[a] = new Array(4);
}

#2


0  

You can do like so:

你可以这样做:

var myArrays = {};
myArrays["arrA"] = new Array(5);
myArrays["anotherArr"] = new Array(8);
...

#1


2  

No you can't (not unless you use Eval() which you shouldn't...).

不,你不能(除非你使用你不应该使用的Eval())。

As Justinas has commented, you could use a Multidimensional array.

正如Justinas所评论的那样,你可以使用多维数组。

var array = [];
array.push(new Array(4));
array.push(new Array(4));
array.push(new Array(4));
array.push(new Array(4));
array.push(new Array(4));
array.push(new Array(4));
array.push(new Array(4));

for(var a = 1; a < 8; a++){
    array[a] = new Array(4);
}

#2


0  

You can do like so:

你可以这样做:

var myArrays = {};
myArrays["arrA"] = new Array(5);
myArrays["anotherArr"] = new Array(8);
...