4

How can I make the code that follows to work?

var x = 'name';

and then, to use the value inside x, as it was a variable, and set it, so that if i want it to be NAME, i'll have the result:

var name = 'NAME';

Is it possible ?

buddy123
  • 5,095
  • 9
  • 45
  • 67
  • 7
    Doing this leads to *really* messy code. – Tom van der Woerdt Jun 24 '13 at 15:10
  • Also resembles http://stackoverflow.com/questions/16985132/parse-a-string-as-an-object-from-data-attribute & http://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key (retrieving objects and variables my string). – Brad Christie Jun 24 '13 at 15:12

2 Answers2

11

Not directly, no. But, you can assign to window, which assigns it as a globally accessible variable :

var name = 'abc';
window[name] = 'something';
alert(abc);

However, a much better solution is to use your own object to handle this:

var name = 'abc';
var my_object = {};
my_object[name] = 'something';
alert(my_object[name]);
Tom van der Woerdt
  • 28,913
  • 7
  • 68
  • 105
6

I haven't seen the rest of your code, but a better way might be to use an object.

var data = {foo: "bar"};
var x = "foo";
data[x]; //=> bar

var y = "hello";
data[y] = "panda";
data["hello"]; //=> panda

I think this is a little cleaner and self-contained than the window approach

Mulan
  • 119,326
  • 28
  • 214
  • 246