Javascript 如何使用动态密钥访问对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6921803/
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-08-23 23:46:29  来源:igfitidea点击:

How to access object using dynamic key?

javascript

提问by Venkat Papana

How to access an object using a variable as key. Here is my code sample:

如何使用变量作为键访问对象。这是我的代码示例:

var o = {"k1": "111", "k2": "222"};
alert(o.k1); //working fine
var key = "k"+1; alert(key); // k1
alert(o.key); //not working

回答by OverZealous

You can access objects like arrays:

你可以访问像数组这样的对象:

alert(o[key]);

回答by Andrius Virbi?ianskas

Change the last line to: alert(o['k1']);or alert(o[key]);where keyis your dynamically constructed property key.

将最后一行更改为:alert(o['k1']);或动态构造的属性键alert(o[key]);在哪里key

Remember you can access object's properties with array notation.

请记住,您可以使用数组表示法访问对象的属性。

回答by Lance

Consider using a for...inloop

考虑使用for...in循环