Saint Dee
Saint Dee

Reputation: 1015

How to convert a value into a variable in jquery?

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

Answers (4)

hyperslug
hyperslug

Reputation: 3623

If you're creating a global variable:

var a = "randomText";
window[a] = "value_of_random_text";

Upvotes: 2

Lufes Puerta
Lufes Puerta

Reputation: 1

eval("var " +a+ " = 'someothervalue';");

It shouldn't be "evil" in this case.

Upvotes: 0

Quentin
Quentin

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

Royi Namir
Royi Namir

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

Related Questions