5

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!

4
  • "I have an array called myArray". In JavaScript, arrays can't have a name. The array you have is anonymous. Commented Dec 19, 2012 at 15:00
  • Show pseudo code of what you mean. Commented Dec 19, 2012 at 15:01
  • I added some code above. Commented Dec 19, 2012 at 15:02
  • 2
    myarray = {} isn't an array, it's an object BTW. Commented Dec 19, 2012 at 15:03

2 Answers 2

7

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]);
Sign up to request clarification or add additional context in comments.

1 Comment

Beat me by 7 seconds. Darn. (not that it's a competition, just found it funny our variance is numbers vs. letters. ;-)
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).

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.