11

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

MetaGuru
  • 42,847
  • 67
  • 188
  • 294
  • Not a duplicate of "Get global variable dynamically by name string in JavaScript", this question doesn't say anything about the variable being global. And it matters. – T.J. Crowder Apr 19 '17 at 09:10

4 Answers4

21

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'];
Ken Browning
  • 28,693
  • 6
  • 56
  • 68
8

You can use

eval(variableString);

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

WoJ
  • 27,165
  • 48
  • 180
  • 345
Mahesh Velaga
  • 21,633
  • 5
  • 37
  • 59
  • More versatile answer. The current best answer can only access properties. This can access both plain variables and properties `eval("x.myproperty");`. Out of curiosity, why is eval not recommended? – Bryant Makes Programs Jan 05 '17 at 15:23
  • 1
    @BryantJackson security is one big reason, you really don't want to create the possibility of arbitrary code execution on a production machine – nickford Apr 03 '17 at 18:34
4

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

window["myVar"]
Gabe Moothart
  • 31,211
  • 14
  • 77
  • 99
3

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

eval('baseVariableName'+index) = 'something';
Dorian Damon
  • 105
  • 3