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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:08:21  来源:igfitidea点击:

get value with string key in javascript

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 stringKeyto get the value valueto 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
}

See: How is a JavaScript hash map implemented?

请参阅:JavaScript 哈希映射是如何实现的?