tags:

views:

166

answers:

4

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

In PHP I can have:

$theVariable = "bigToe";
$bigToe = "is broken";

such that:

echo "my ".$theVariable." ".$$theVariable;

would display

my bigToe is broken

How would I go about doing something similar to that in JavaScript?

+1  A: 

Simply

eval("variableName")

Although you have to be sure you know the exact value your evaling as it can be used for script injection if you're passing it untrusted content

olliej
You definitely should't use eval
Fabien Ménager
+1 wrong downvote compensated. eval is the only way to reference a local variable and the only formally correct answer to the OPs question. The whole idea is, of course, wrong, but that's another story.
stereofrog
@Fabien: I know that eval has a huge number of security risks, i even commented explicitly to that effect. That said the only way to achieve what was requested is eval, saying "you definitely shouldn't use eval" implies that my answer should have been "it's impossible" which is clearly wrong.
olliej
+5  A: 

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

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

Eli
+1  A: 

One way is to use the eval function

var theVariable = "bigToe";
var bigToe = "is broken";
console.log('my '+theVariable+' '+eval(theVariable));

Another way is to use the window object, which holds the key-value pair for each global variable. It can accessed as an array:

var theVariable = "bigToe";
var bigToe = "is broken";
console.log('my '+theVariable+' '+window[theVariable]);

Both methods print the answer to the Firebug console.

DavidWinterbottom
the "window" option is the best. If your var is not in the global scope (for example declared in a function), you should replace "window" by "this", or the containing object name
Fabien Ménager
@Fabien: if the var is not in the global scope, then using 'this' as a prefix will not help you -- the only reason that 'this' and 'window' are often interchangable is because 'this' is always the global object when a function is called without a base and window is merely an alias to that global object.
olliej
+2  A: 

I would use the window array instead of eval:

var bigToe = "big toe";
window[bigToe] = ' is broken';
alert("my " + bigToe + window[bigToe]);
karim79
Why would you prefer the window[] over eval()?
baiano
@baiano: Removes any security worries that are introduced with `eval`'s usage, plus referencing a dictionary is *always* faster then evaluating Javascript just to produce a solution.
Jed Smith
@baiano - simply because I always tend to avoid using `eval` if I can possibly help it. See http://stackoverflow.com/questions/86513/why-is-using-javascript-eval-function-a-bad-idea
karim79
window[] doesn't work with local variables.
stereofrog