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?
This should do it:
var sample = new Array();
sample[0] = 'one';
sample[1] = 'two';
var arrayname = "sample";
var number = window[arrayname][1];
alert(number);
var sample = new Array();
sample[0] = 'one';
sample[1] = 'two';
var obj = {"sample": sample}
var arrayname = "sample";
var number = obj[arrayname][1];
I mean you can use eval, but it is not the best approach:
eval("var arrayname = sample");
var number = arrayname[1];
Why not just do:
var arrayname = sample;
var number = arrayname[1];
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).
You could use something like:
var arrayName = "sample",
number = window[arrayname][1];
Out of my head...
First declare some global variable
var buf;
Then
var sample = new Array();
sample[0] = 'one';
sample[1] = 'two';
var arrayname = "sample";
eval('buf=' + arrayname + ';');
var number = buf[1];
Damn undesirable way but does what you want...