user2870240
user2870240

Reputation: 1

accessing an array through a string

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?

Upvotes: 0

Views: 53

Answers (3)

user2823603
user2823603

Reputation:

try to use the eval function

instead of

alert(foo);

use

alert(eval(foo));

Upvotes: 0

letiagoalves
letiagoalves

Reputation: 11302

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);
}

Upvotes: 1

VisioN
VisioN

Reputation: 145398

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"

Upvotes: 3

Related Questions