Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: access array with the same name as a variable? [duplicate]

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:

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

Thanks!

like image 223
user1856596 Avatar asked Dec 19 '12 14:12

user1856596


2 Answers

The key here is bracket notation.

If myArray is global

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]);
like image 78
epascarello Avatar answered Nov 14 '22 22:11

epascarello


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

arr = window[myVar] // assuming myArray is a global variable
arr[0] = 5 // same as myArray[0] = 5
like image 22
Artem Sobolev Avatar answered Nov 14 '22 21:11

Artem Sobolev