Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript's equivalent to PHP's $$varName [duplicate]

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?

like image 406
Aaron Luman Avatar asked Oct 31 '09 21:10

Aaron Luman


4 Answers

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

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

like image 123
Eli Avatar answered Nov 07 '22 18:11

Eli


I would use the window array instead of eval:

var bigToe = "big toe";
window[bigToe] = ' is broken';
alert("my " + bigToe + window[bigToe]);
like image 40
karim79 Avatar answered Nov 07 '22 20:11

karim79


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

like image 1
olliej Avatar answered Nov 07 '22 20:11

olliej


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.

like image 1
DavidWinterbottom Avatar answered Nov 07 '22 19:11

DavidWinterbottom