Using a variable value to call an array element

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?

var sample = new Array();
sample[0] = 'one';
sample[1] = 'two';

var arrayname = "sample";
var number = arrayname[1];  ///  Something like this, although I realize this doesn't work for obvious reasons...

I've read other questions in regards to using an variable value as a function, but I didn't understand the approach or even if this would work for the above situation.

Thanks in advance!!

Answers:

Answer

This should do it:

    var sample = new Array();
    sample[0] = 'one';
    sample[1] = 'two';

    var arrayname = "sample";
    var number = window[arrayname][1];
    alert(number);
Answer

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).

Answer

You could use something like:

var arrayName = "sample",
    number = window[arrayname][1];
Answer

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];  
Answer

If it's in the global scope, you can access your array by doing

var sample = new Array();
sample[0] = 'one';
sample[1] = 'two';
var arrayname = "sample";
var number = (window[arrayname])[1]
Answer
var sample = new Array();
sample[0] = 'one';
sample[1] = 'two';
var obj = {"sample": sample}

var arrayname = "sample";
var number = obj[arrayname][1];
Answer

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...

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.