3

I have a problem that I hope to use one variable's contents as another variables name in javascript. In this case, I do not know what is the contents in that variable, I only know it is a text type and I hope the variable I need to declare will use that text as its name.

Anyone could kindly give me some suggestion of how to do that?

Thank you!

Arthur0902
  • 209
  • 3
  • 14
  • Like dynamic variables? check out http://stackoverflow.com/questions/2413414/is-there-an-easy-way-to-create-dynamic-variables-with-javascript#2413453 – JKirchartz Sep 19 '12 at 17:35

2 Answers2

3

You can't really, variable names (identifiers) are static (as long as you don't use eval) in a scope.

However, you can easily use objects for that. Accessing properties of them with a variable name is easy, use the bracket notation:

var obj = { someprop:"someval", otherprop:… },
    name = "someprop";
obj[name]; // "someval"

If you need a global variable, you can do that by accessing it as a property of the global object (in browsers: window):

variable = "someval";
var name = "variable";
window[name]; // "someval"
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
3

You are able to use a variable's value as another variable's name as long as the latter variable can be accessed via bracket notation, e.g.

var firstVariable = 'secondVariable';

window[firstVariable] = 'secondValue';
// you now have a global variable 
// named "secondVariable" with the value "secondValue"

Note I would not recommend cluttering the global namespace like this; it was just for demonstration.

jbabey
  • 45,965
  • 12
  • 71
  • 94