【问题标题】:Use variable as object key [duplicate]使用变量作为对象键[重复]
【发布时间】:2019-07-16 01:21:24
【问题描述】:

我希望将变量插入到对象键结构中,但我只得到变量名而不是变量值。

var winnerId = 10;
var loserId = 11;        

newMessage.setMessageData({
  winnerId : {
    "status" : "win",
    "choice" : playerData[winnerId]["currentChoice"],
    "newScore" : playerData[winnerId]["score"]
  },
  loserId : {
    "status" : "lost",
    "choice" : playerData[loserId]["currentChoice"],
    "newScore" : playerData[loserId]["score"]
  }           
});

【问题讨论】:

  • 我觉得自己有点破纪录,但指出您所描述的内容与 JSON 无关,总是感觉有用。它只是一个普通的旧 object。 JSON 是一个string,它表示一个对象。
  • 很高兴知道谢谢。我相信它已经说过很多次了:-)

标签: javascript


【解决方案1】:

你应该使用computed-property-names:

newMessage.setMessageData({
    [winnerId]: {
        "status": "win",
        "choice": playerData[winnerId]["currentChoice"],
        "newScore": playerData[winnerId]["score"]
    },
    [loserId]: {
        "status": "lost",
        "choice": playerData[loserId]["currentChoice"],
        "newScore": playerData[loserId]["score"]
    }
});

【讨论】:

  • 我收到无效的属性 ID (#114) 错误
  • @KeithPower 它应该可以工作,你能发布更多的代码细节吗?
猜你喜欢
  • 2015-08-30
  • 2011-12-11
  • 2020-02-18
  • 2012-09-21
  • 2011-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-17
相关资源
最近更新 更多