Variable Name Made Of A Variable Value
How can i use a variable value to name a variable? var xyz = 'test'; var (xyz) = 'abc'; alert (test);
Solution 1:
If you put them in an object, you could do this instead:
var Container = {};
var xyz = "test";
Container[xyz] = "abc";
alert(Container['test']);
Solution 2:
A variable name can not be the result of an expression unless you use eval
, which you don't want to do, or unless it's a global variable.
If you need dynamic naming, you should use an object, and name its properties dynamically. This is also how globals can be dynamically created.
var xyz = "test";
//globalwindow[xyz] = "abc";
alert(test); // "abc"// object propertyvar myData = {};
myData[xyz] = "abc";
alert(myData.test); // "abc"
Solution 3:
eval does this:
xyz = "test";
eval(xyz+"=123");
alert(test); // gives 123
I am sure many say NO to eval. But, this does it.
Solution 4:
If it is global scope
var xyz = "test";
window[xyz] = "abc";
alert (test);
Better to use an object
var myObject = {};
var xyz = "test";
myObject [xyz] = "abc";
alert (myObject.test);
Solution 5:
var xyz = "test";
eval ( xyz + "= 'abc';");
alert (test);
Post a Comment for "Variable Name Made Of A Variable Value"