MetaGuru
MetaGuru

Reputation: 43843

Is there a way to access a javascript variable using a string that contains the name of the variable?

This way I could have a function that says whatever_way_you_do_this = something. Is this possible? Basically I could tell a function which variable I want to set by giving it a string that holds the name of the variable.

Thanks

Upvotes: 12

Views: 16381

Answers (4)

Mahesh Velaga
Mahesh Velaga

Reputation: 21971

You can use

eval(variableString);

Proceed with caution as many don't recommend using eval()

Upvotes: 9

Dorian Damon
Dorian Damon

Reputation: 95

The eval function can access a variable from a string containing the variable's name.

eval('baseVariableName'+index) = 'something';

Upvotes: 3

Ken Browning
Ken Browning

Reputation: 29091

Given:

var x = {
    myproperty: 'my value'
};

You can access the value by:

var value = x['myproperty'];

If you're looking for a global variable, then you would check its container (window);

var value = window['x']['myproperty'];

Upvotes: 22

Gabe Moothart
Gabe Moothart

Reputation: 32082

If it is a global variable named myVar, you can use:

window["myVar"]

Upvotes: 5

Related Questions