0

I've been having a problem with accessing an array. I want to access the value of an array but all I've been getting is the string name of the array. I've searched the net but have found nothing related to my problem. I've simplified the problem and it looks like this.

var pics = ["one","two","three"];
var index = 1;
var name = "pics";

function changeContent(name)
{
    var foo = name+'['+index+']'; 
    alert(foo);
}

All I've been getting is

   pics[1]

What I want is the value of pics[1] which is "two". How do you get the value of the array?

  • possible duplicate of [Access value of JavaScript variable by name?](http://stackoverflow.com/questions/4399794/access-value-of-javascript-variable-by-name) – deceze Oct 11 '13 at 09:05

3 Answers3

3

In order not to use globals or eval access array from the local object:

var arrays = {
    pics: ["one", "two", "three"]
};

function changeContent(name) {
    return arrays[name][index];
}

var index = 1,
    name = "pics";

console.log(changeContent(name));  // "two"
VisioN
  • 143,310
  • 32
  • 282
  • 281
1

If you are in global scope you can do it like this:

var pics = ["one","two","three"];
var index = 1;
var name = "pics";

function changeContent(name)
{
    var foo = window[name][index]; 
    alert(foo);
}
letiagoalves
  • 11,224
  • 4
  • 40
  • 66
0

try to use the eval function

instead of

alert(foo);

use

alert(eval(foo));
  • 1
    [Bad attitude](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Don.27t_use_eval.21). – VisioN Oct 11 '13 at 09:11