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?
There is a pretty good write-up on Dynamic Variables in JavaScript here:
http://www.hiteshagrawal.com/javascript/dynamic-variables-in-javascript
I would use the window
array instead of eval
:
var bigToe = "big toe";
window[bigToe] = ' is broken';
alert("my " + bigToe + window[bigToe]);
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With