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 ?
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]);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With