0

I am trying to call a string variable to reference an array variable.

message1[0][0] = "Hello."; // existing array
var caller = ['message1', 'message2', 'message3'];

alert(message1[0][0]);

But instead of using the message1 array in the alert, I want to use caller[0] (which is equal to "message1") so that it displays "Hello". How do you do this? This doesn't seem to work:

alert(caller[0][0][0]);
2
  • message1[caller[0]], but you really want an plain Object I think. Commented Jan 1, 2015 at 7:52
  • Note: You don't call variables. You use them, access them, refer to them, get them, set them... You call functions. Commented Jan 1, 2015 at 7:56

1 Answer 1

2

The best way is to put message1 on an object, then use [] notation to index into the object:

var obj = {
  message1: [
    ["Hello.", "two", "three"]
    ]
};
var caller = ['message1', 'message2', 'message3'];

alert(obj[caller[0]][0][0]);

If message1 is a global variable, it's already on an object — the global object, which you can access as window on browsers. So if it's a global, you could use:

alert(window[caller[0]][0][0]);

But global variables are a Bad Idea(tm), so best to use your own object instead.


Full disclosure: You can also use eval to do it, but it's a big hammer for a task this small. Just for completeness:

alert(eval(caller[0] + "[0][0]"));

I don't recommend it, but provided you're fully in control of the text you pass into it, it's workable. Much better to use an object, though.

Sign up to request clarification or add additional context in comments.

5 Comments

The first one is the best way what I think.
And that's why it's first. :-)
This is a very good answer, and it already worked as a global variable, but I want to use the object one, and it doesn't seem to work yet. So: message1 starts out as a blank array. My question is, do you declare the array inside the object like this: message1: []?
@ken_vitreous: Yup. It's much the same as an assignment statement, but with a : instead of a =. The bit after the : can be any expression, including an empty array. (That thing is called a "property initialiser"; the {...} thing is an "object initialiser" [sometimes called an "object literal"].) Best,
The explanations are very insightful. Thanks a lot!

Your Answer

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.