问题
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