• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

JS 通过变量调用对象属性

用户头像
it1352
帮助1

问题说明

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

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 

正确答案

#1

使用 括号表示法:

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

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcebhkc
系列文章
更多 icon
同类精品
更多 icon
继续加载