在 Javascript 中使用枚举
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9528800/
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 Enums In Javascript
提问by user1219627
I have the following ENUM in my Javascript:
我的 Javascript 中有以下 ENUM:
var letters = { "A": 1, "B": 2, "C": 3.....}
And to use this I know use:
要使用它,我知道使用:
letters.A
But I was wondering if there was a way that i could replace A with a variable. I have tried something like
但是我想知道是否有一种方法可以用变量替换 A 。我试过类似的东西
var input = "B";
letters.input;
but this does not work.
但这不起作用。
Any suggestions?
有什么建议?
Thanks
谢谢
回答by Paul
You can use the Bracket Notation Member Operator:
您可以使用括号符号成员运算符:
letters[input];
It expects a string, so letters.B == letters["B"]
, and:
它需要一个字符串,所以letters.B == letters["B"]
,并且:
var letters = { "A": 1, "B": 2, "C": 3 },
input = "B";
console.log(letters[input]);
outputs 2
.
输出2
。