Javascript is equivalent to PHP $$ varName

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; 

will be displayed

 my bigToe is broken 

How do I do something similar to JavaScript?

+6
javascript php variable-variables
source share
4 answers

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

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

+5
source share

I would use the window array instead of eval :

 var bigToe = "big toe"; window[bigToe] = ' is broken'; alert("my " + bigToe + window[bigToe]); 
+3
source share

Just

 eval("variableName") 

Although you have to be sure that you know the exact meaning of your evasion, as it can be used to inject a script if you pass untrusted content to it

+1
source share

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 a window object that contains a key-value pair for each global variable. It can be accessed as an array:

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

Both methods print a response to the Firebug console.

+1
source share

All Articles