Reputation: 1015
I have searched about this but can't seem to find exactly how to do it. Is there a simple way to directly convert the value into a variable? This illustration may help you understand my problem.
var a = "randomText";
var randomText = "someothervalue";
I have read about eval() but it says it's not recommended to use since it's 'evil'.
Please help. thanks.
Upvotes: 1
Views: 135
Reputation: 3623
If you're creating a global variable:
var a = "randomText";
window[a] = "value_of_random_text";
Upvotes: 2
Reputation: 1
eval("var " +a+ " = 'someothervalue';");
It shouldn't be "evil" in this case.
Upvotes: 0
Reputation: 943579
If you have a set of data that you need to access by name, then use a proper data structure instead of floating a bunch of variables around. Use an object.
var someObject = {};
someObject['foo'] = 123;
var propertyName = 'foo';
alert(someObject[propertyName]);
Upvotes: 3
Reputation: 148524
You cant use it without EVAL.
Anad Evals bad Side is Mostly with Injection.
dont Get Confused. Its Not Evil.
jQuery Uses This a Lot. (e.g. json...)
Upvotes: 0