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

arrays, javascript

Solution

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]);

Problem

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!

Original source

Related problems