javascript 为传递的值获取对应的 eNum 键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6215349/
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
Getting corresponding eNum key for the value passed
提问by John Cooper
var StateValue = {
Unknown: 0,
AL: 1,
AK: 2,
AZ: 3,
AR: 4,
CA: 5,
CO: 6,
CT: 7,
DE: 8,
},
Now i need to get the enumValues.
现在我需要获取 enumValues。
function getKeyValue(stateVal) {
For example 'AK'
I need to get the corresponding value...
}
回答by Felix Kling
It is simply:
很简单:
var val = StateValue[stateVal];
You can access object properties with bracket notation.
您可以使用括号表示法访问对象属性。
I suggest to read MDC - Working with Objects.
我建议阅读MDC-使用对象。
回答by bokkie
To answer the question in the title (in case someone comes for that), and not the one in the description, you can get the key by the value like this:
要回答标题中的问题(以防有人为此而来),而不是描述中的问题,您可以通过如下值获取键:
Object.keys(StateValue).find(
key => StateValue[key] === 2
)
this will return AK
这将返回 AK
回答by Sam Jones
var val = StateValue.AK
would return 2
, just like a regular ENUM
var val = StateValue.AK
会返回2
,就像一个普通的 ENUM