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

Please have a look on 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 prefix to a function and the try to print some pre-defined values by concatenating. But the above example just prints "abc_text" and "def_text" .. instead of "Hello" and "world". How can I get it working?

Thank you.

EDIT

I am using Jquery.

Answers:

Answer

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


var text = {"abc" : "Hello", "def" : "Word"};

Answer

in this case use

var xyz = window[elem+"_text"];
Answer
var test={"abc":"Hello", "def":"World"};

function testMe(elem) { 
    var xyz = test[elem];
    alert(xyz); 
} 

testMe("abc"); 
testMe("def");

?

Answer

There is a pretty good write-up on Dynamic Variables in JavaScript here:

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.