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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:42:16  来源:igfitidea点击:

Getting a Custom Objects properties by string var

javascriptpropertiescustom-object

提问by Jay-Nicolas Hackleman

Possible Duplicate:
javascript object, access variable property name?

可能重复:
javascript 对象,访问变量属性名称?

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] ;