【问题标题】:Accessing object key via dynamically changed variable key [duplicate]通过动态更改的变量键访问对象键[重复]
【发布时间】:2019-02-12 00:18:31
【问题描述】:

我不确定如何在标题中正确解释,但情况如下:

具有三个可用角度:前、左和右:

captures: {
  front: { img: '', correct: false },
  left: { img: '', correct: false },
  right: { img: '', correct: false }
},

我已经定义了一个名为this.currentAngle = 'front'的默认变量。

我想从 currentAngle 内的 CAPTURES 对象列表中访问一个值。

这不起作用:

this.captures.[this.currentAngle].img

逻辑上也不是这个

this.captures.this.currentAngle.img

正确的做法是什么?

【问题讨论】:

  • this.captures[this.currentAngle].img
  • 几乎:this.captures[this.currentAngle].img
  • @connexo 哦,你的速度打字机!!! ;)

标签: javascript arrays object vue.js


【解决方案1】:

你几乎明白了,只需从第一次尝试中删除左方括号之前的点:

const captures = {
  front: { img: 'f', correct: false },
  left: { img: 'l', correct: false },
  right: { img: 'r', correct: false }
}

let prop = 'front'

console.log(captures[prop].img)

【讨论】:

    猜你喜欢
    • 2022-07-28
    • 1970-01-01
    • 2012-07-15
    • 2020-06-26
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 2014-10-11
    • 2012-09-21
    相关资源
    最近更新 更多