Reputation: 1
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
Reputation:
try to use the eval function
instead of
alert(foo);
use
alert(eval(foo));
Upvotes: 0
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
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