Want to play with a variable who’s name you don’t (yet) know at runtime? So did I. Here’s how:
var sheep = "dynamicVariableName";
eval("var " + sheep + " = 'beehh'");
alert(dynamicVariableName);
Result: Shows alert windows with text “beehh”.
You can also do the same with arrays:
var sheep= "dynamicVariableName";
eval("var " + sheep + "= new Array();");
Speed? Eval is VERY fast.
Security considerations? Think twice before passing user submitted code to eval. Use some form of string escaping if you do.
Thank you for clear explanation!
Thanks this was perfect. I used it to set multiple counters dynamically:
var counterName = modelName + “Counter”;
eval(“if (typeof ” + counterName + ” != ‘number’){ ” + counterName + ” = 1;}”);
then
eval(counterName + “++”);
to render.