简体   繁体   中英

Calling a variable to reference an array

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM