JS 通过变量调用对象属性 [英] JS Calling Object Property by Variable

查看:105
本文介绍了JS 通过变量调用对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我有一个对象并且我想引用其中的一个属性时,我可以使用例如

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

显然这是行不通的.该变量被解释为一个字符串本身并要求带键的值:myvar".

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 

并被解释为

var myvar = qwertz; objectName.qwertz.propertyName 

推荐答案

使用 括号表示法:

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

这篇关于JS 通过变量调用对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆