Gus
Gus

Reputation: 943

Jquery how to assign the name of variable (dynamically)

To assign a value to a variable is very simple just do it this way

var foo = "bar";

But to assign a name to the variable (dynamically) as you have to do?

var variableName = "newName";
var variableName = "bar";    // in this case assign new value of variableName

Do I have to do it this way?

var foo + "_" + variableName = "foo"  // foo_newName = "bar"

Upvotes: 0

Views: 9984

Answers (3)

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28445

As per my understanding, you can not create variables like this, however, you can use object and set its property.

var foo = "bar";
var variableName = "newName";

window[foo + "_" + variableName]  = "foo" ;
console.log(bar_newName);

or

var foo = "bar";
var variableName = "newName";

var obj = {};

obj[foo + "_" + variableName]  = "foo" ;
console.log(obj["bar_newName"]);

Upvotes: 2

Tariq
Tariq

Reputation: 2871

You can do that by using eval(), but there are some Reservations about using that method:

eval("foo_" + i + "='bar'")

Upvotes: 4

Romnick Susa
Romnick Susa

Reputation: 1288

You can make dynamic variable using this way

window['varname'] = "test";

alert(varname);

Upvotes: 10

Related Questions