Javascript 通过字符串 var 获取自定义对象属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7068968/
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 a Custom Objects properties by string var
提问by Jay-Nicolas Hackleman
Possible Duplicate:
javascript object, access variable property name?
Trying to get more advanced in my JS...
试图在我的 JS 中变得更先进......
I have a custom object:
我有一个自定义对象:
Object myObject = new Object();
myObject.thing = anythingHere;
I would like to be able to retrieve a custom objects property by passing in a string... eg:
我希望能够通过传入一个字符串来检索自定义对象属性......例如:
var propertyString = 'thing';
alert(myObject.propertyString);
I can't quite figure that out. I've looked at a number of tutorials for custom objects - but nothing shows how to get properties that I don't know the names of... Also - I would like to avoid looping through all properties if possible...
我不能完全弄清楚。我已经查看了许多自定义对象的教程 - 但没有任何内容显示如何获取我不知道名称的属性......此外 - 如果可能的话,我想避免遍历所有属性......
Thanks!!!
谢谢!!!
回答by ldiqual
Simply use myObject['thing']
.
只需使用myObject['thing']
.
回答by Ryan
You could use:
你可以使用:
myObject[propertyString] ;