JS Calling Object Property by Variable

牧云@^-^@ 提交于 2021-02-05 11:10:23

问题


When I have an object and I want to refer to a property within it, I can use e.g.

objectName.propertyName 

and when I have a "subproperty" I can use

objectName.propertyName.propertyName

But how can I use a variable with this syntax ?

objectName.myvar.propertyName

Obviously this does not work. The variable is interpreted as a string itself and calls for the value with the key: "myvar".

How do I have to declare the variable using this syntax to be used like this:

var myvar = qwertz; objectName.myvar.propertyName 

and be interpreted as

var myvar = qwertz; objectName.qwertz.propertyName 

回答1:


Use the bracket notation:

var myvar = 'qwertz';
var result = objectName[myvar].propertyName; 
// equivalent to objectName.qwertz.propertyName


来源:https://stackoverflow.com/questions/21799972/js-calling-object-property-by-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!