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
  • 41,117
  • 66
  • 181
  • 290
  • 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

20

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,003
  • 6
  • 55
  • 67
7

You can use

eval(variableString);

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

WoJ
  • 23,237
  • 42
  • 145
  • 273
Mahesh Velaga
  • 21,059
  • 5
  • 35
  • 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 James 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
  • 30,215
  • 13
  • 74
  • 98
2

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

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