user1365010
user1365010

Reputation: 3343

Access value of variables

We can call variables by their names like this :

var name="a";
var a=4;
eval("alert("+name+")");//this will alert 4

But I heard that eval is not recommended. Is there a way to call variables by their names without eval ?

Upvotes: 2

Views: 78

Answers (2)

James Allardice
James Allardice

Reputation: 165951

You are right, eval is definitely not recommended. A common way is to make them properties of an object, and then use square bracket notation to access them:

var name = "a";
var myObj = {
    a: 4
};
alert(myObj[name]);

Here's a working example.

Upvotes: 4

gen_Eric
gen_Eric

Reputation: 227210

If the variables are global, you can do window[name], but otherwise, no you cannot that. "Variable variables" is a PHP thing.

If you want to do this, change your program, so that your variables are stored in an object.

var vars = {
    a: 4
};
var name = "a";

alert(vars[name]);

Upvotes: 1

Related Questions