1

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.

1
  • 2
    This all sounds like the wrong approach. Why do you need variable variable names? Commented Jun 14, 2009 at 15:32

4 Answers 4

6

in this case use

var xyz = window[elem+"_text"];
Sign up to request clarification or add additional context in comments.

8 Comments

This (or alternately eval) is right. But wbdvlpr, note that it's rarely necessary to do this in well-written code.
eval is evil. eval should only ever be used in the rarest of situations. It is far too easy to get code injected from other sources.
@Jonathan: uh... well, no. It's only easy if you're accepting input from untrusted sources and then blindly passing it to eval(). But it's slow and in this case unnecessary; surely that's reason enough!
@Jonathan Fingland - yes, it works. But associative array seems better to me. Thanks.
@wbdvlpr, oh I agree. the question as asked is solved by the window[] method, but the associative array method is better practice overall
|
4

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"};

2 Comments

just to make erenon's point clearer. it would be accessed using, for example, var xyz = text[elem];
Thanks @erenon, and Thanks, again, Jonathan Fingland, for its usage code.
3
var test={"abc":"Hello", "def":"World"};

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

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

Comments

1

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

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

Comments

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.