I have a string variable which contains the name of an array. What I\'d like to do is access an element of that array. And write it to another variable. How can I do this?
There's no universal way in JavaScript to do exactly what you've got set up there, but you can use string variables to access object properties in a dynamic way.
var objArr = { array1: [], array2: [] };
Now you can use a variable with the value "array1" or "array2" to get at those arrays:
var name = "array2";
objArr[name].push(14);
What you cannot do in JavaScript is access local variables by a dynamic name, or indirectly if you prefer. You can access global variables that way if you have a name for the global context, which in a browser is the window
object:
window[ name ].push(17);
However there's no way to get a similar name for a local scope.
edit — @Neal points out (and is downvoted mercilessly) that eval()
can do what you want, but a lot of people recommend staying far away from eval()
unless it's absolutely unavoidable (which is really rare). I've trained myself to ignore it so well that I always forget about it when questions like this are asked (which is, oddly, quite often on SO, though in my programming practice I never find myself wanting to do this).