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?

1

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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);
}
answered Oct 11, 2013 at 9:06

Comments

0

try to use the eval function

instead of

alert(foo);

use

alert(eval(foo));
answered Oct 11, 2013 at 9:09

1 Comment

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.