javascript 在JS中使用字符串作为变量名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17278858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using string as variable name in JS?
提问by buddy123
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:
然后,使用 x 中的值,因为它是一个变量,并设置它,以便如果我希望它是 NAME,我将得到结果:
var name = 'NAME';
Is it possible ?
是否可以 ?
回答by Tom van der Woerdt
Not directly, no. But, you can assign to window
, which assigns it as a globally accessible variable :
不直接,不。但是,您可以分配给window
,它将其分配为全局可访问变量:
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]);
回答by Thank you
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
我认为这比window
方法更清洁和独立