JavaScript:访问与变量同名的数组? [重复]

时间:2022-08-27 17:37:33

Possible Duplicate:
Get variable from a string

可能重复:从字符串中获取变量

I have an array called myArray and a variable which is called myVar. The myVar variable holds a value 'myArray' (value of myVar equals the arrays name). Can I somehow access the arrays elements using the myVar variable? Some code to explain what I mean:

我有一个名为myArray的数组和一个名为myVar的变量。 myVar变量包含值'myArray'(myVar的值等于数组名称)。我可以使用myVar变量以某种方式访问​​数组元素吗?一些代码来解释我的意思:

var myArray = {1, 2, 3};
var myVar = "myArray";

Thanks!

2 个解决方案

#1


7  

The key here is bracket notation.

这里的关键是括号表示法。

If myArray is global

如果myArray是全球性的

var myArray  = ["1","2","3"];
var myVar = "myArray";
console.log(window[myVar]);

better to use a namespace

更好地使用命名空间

var myData = {};
myData.myArray  = ["1","2","3"];
var myVar = "myArray";
console.log(myData[myVar]);

#2


3  

If your array (myArray) is a global variable, then you can use window[myVar]. If it is a local variable, then the only way is to use eval(myVar) (or its analogs).

如果你的数组(myArray)是一个全局变量,那么你可以使用window [myVar]。如果它是局部变量,那么唯一的方法是使用eval(myVar)(或其类似物)。

arr = window[myVar] // assuming myArray is a global variable
arr[0] = 5 // same as myArray[0] = 5

#1


7  

The key here is bracket notation.

这里的关键是括号表示法。

If myArray is global

如果myArray是全球性的

var myArray  = ["1","2","3"];
var myVar = "myArray";
console.log(window[myVar]);

better to use a namespace

更好地使用命名空间

var myData = {};
myData.myArray  = ["1","2","3"];
var myVar = "myArray";
console.log(myData[myVar]);

#2


3  

If your array (myArray) is a global variable, then you can use window[myVar]. If it is a local variable, then the only way is to use eval(myVar) (or its analogs).

如果你的数组(myArray)是一个全局变量,那么你可以使用window [myVar]。如果它是局部变量,那么唯一的方法是使用eval(myVar)(或其类似物)。

arr = window[myVar] // assuming myArray is a global variable
arr[0] = 5 // same as myArray[0] = 5