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?

2

3 Answers 3

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

Comments

0

Use:

eval("myArray")

It is an array which has the contents of myArray.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.