How to access javascript variable value by creating another variable via concatenation?

Please look at the following code -

var abc_text = "Hello"; var def_text = "world"; function testMe(elem) { var xyz = elem+"_text"; alert(xyz); } testMe("abc"); testMe("def"); 

I am trying to pass a prefix to a function and trying to print some predefined values โ€‹โ€‹by concatenation. But the above example just prints "abc_text" and "def_text" .. instead of "Hello" and "world". How can I make it work?

Thanks.

EDIT

I am using jQuery.

+1
javascript
source share
4 answers

You can eval xyz, but it is better to store abc_text and def_text in an associative array or in an object;

 var text = {"abc" : "Hello", "def" : "Word"}; 
+4
source share

in this case use

 var xyz = window[elem+"_text"]; 
+6
source share
 var test={"abc":"Hello", "def":"World"}; function testMe(elem) { var xyz = test[elem]; alert(xyz); } testMe("abc"); testMe("def"); 

+3
source share

There is a pretty good entry in dynamic variables in JavaScript:

http://www.hiteshagrawal.com/javascript/dynamic-variables-in-javascript

+1
source share

All Articles