How can i concatenate var names to declare new vars in javascript?:
var foo = 'var';
var bar = 'Name';
How can i declare variable varName?
How can i concatenate var names to declare new vars in javascript?:
var foo = 'var';
var bar = 'Name';
How can i declare variable varName?
Try something like:
window[foo + bar] = "whatever";
alert(varName);
do not use the eval function unless you are absolutely certain about what's going in. window[] is much safer if all you're doing is variable access
WARNING: VaporCode! Off the top of my head...
window[foo + bar] = "contents of variable varName";
Does that work?
To dynamically declare a local variable (i.e. var fooName
), I guess you could use eval
:
eval('var ' + foo + bar);
Best to avoid eval
though, if you can avoid it (see related question).
A better way is to set an object property. Defining a global variable is equivalent to setting a property on the global object window
:
window[foo+bar] = 'someVal';
You can substitute window
for another object if appropriate.
there may be a better way but eval should do it
eval('var ' + foo + bar);