javascript 在javascript中使用字符串键获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17116032/
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
get value with string key in javascript
提问by CorayThan
I can't figure out how to get an object property using a string representation of that property's name in javascript. For example, in the following script:
我无法弄清楚如何在 javascript 中使用该属性名称的字符串表示来获取对象属性。例如,在以下脚本中:
consts = {'key' : 'value'}
var stringKey = 'key';
alert(consts.???);
How would I use stringKey
to get the value value
to show in the alert?
我将如何使用stringKey
来获取value
在警报中显示的值?
回答by MrCode
Use the square bracket notation []
使用方括号表示法 []
var something = consts[stringKey];
回答by Jóni Louren?o
Javascript objects are like simple HashMaps:
Javascript 对象就像简单的 HashMap:
var consts = {};
consts['key'] = "value";
if('key' in consts) { // true
alert(consts['key']); // >> value
}