2

I have a JS array.

//This is Dynamic, I maynot know the name in the beginning
var myArray = ["apple","ball","cat"];

var NameOfArray = "myArray";

How can I access myArray if I know only it's name in the form on String? In PHP, I would use $$. How Do I do that in JS?

tika
  • 7,135
  • 3
  • 51
  • 82

3 Answers3

3

Depending on where the array is defined, you can access it directly i.e. if it is defined globally as in your example:

console.log(window[NameOfArray][1]); // Outputs "ball"
rdubya
  • 2,916
  • 1
  • 16
  • 20
0

Use:

eval("myArray")

It is an array which has the contents of myArray.

user3581203
  • 297
  • 1
  • 2
  • 13
0

If you're able to control the name of the variable NameOfArray, i.e. control the code, you could just set it as a variable on the window in that line using eval

var myArray = [1,2,3];
window.theArrayIWant = eval('myArray');

then using theArrayIWant moving forward

Antony Koch
  • 2,043
  • 1
  • 16
  • 23