Javascript ‘Variable’ Variables
by Gabi SolomonIf you havent figure it out by now, my "expertise" is more on the back-end ( php & mysql ) than with front end. So i sometimes look for solutions in javascript that i know how to do in php.
One of this is the concept of variable variables. A ‘variable’ variable is when the identifier of a variable is a variable itself. To be more specific, this works by taking a string as the name, and then defining a variable with that name. That variable can then be used as a normal variable.
The solution in Javascript
1. Using Eval
the first solution i found was to use eval.
-
var x='street';
-
eval('name_' + x + ' = "Lincon Road"');
-
document.write('got ' + name_street);
This should result in having a variable name_street with the value Lincon Road.
However from my small knowledge of JS, i have come to understand that you should avoid using eval when possible.
2. Better Solution - Using Window Array
-
var x='street';
-
window['name_' + x] = 'Lincon Road';
-
document.write('got ' + name_street);
Same effect, with no eval
This is all for today,
cheers
Related Posts
-
http://www.vibramshoesonline.com vibram fivefingers

