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?deceze– deceze ♦2013年10月11日 09:05:29 +00:00Commented Oct 11, 2013 at 9:05
3 Answers 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"
answered Oct 11, 2013 at 9:04
VisioN
146k35 gold badges287 silver badges291 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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);
}
answered Oct 11, 2013 at 9:06
letiagoalves
11.3k4 gold badges43 silver badges68 bronze badges
Comments
try to use the eval function
instead of
alert(foo);
use
alert(eval(foo));
answered Oct 11, 2013 at 9:09
user2823603
1 Comment
VisioN
lang-js