Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using string as variable name in JS? [duplicate]

Tags:

javascript

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 ?

like image 313
buddy123 Avatar asked Dec 02 '22 22:12

buddy123


2 Answers

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]);
like image 174
Tom van der Woerdt Avatar answered Dec 18 '22 21:12

Tom van der Woerdt


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

like image 43
Mulan Avatar answered Dec 18 '22 21:12

Mulan