在JS中使用string作为变量名?

在JS中使用string作为变量名?

问题描述:

如何使后续代码生效?

var x = 'name';

然后,使用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';

有可能吗?

不直接,没有。但是,您可以分配到窗口,它将其指定为全局可访问的变量:

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]);