温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - How to traverse the attribute name plus [i] to count?
javascript

javascript - 如何遍历属性名称加[i]进行计数?

发布于 2020-03-27 10:27:44

例如,对象的属性名称有一个数字,我想为遍历对象添加一个属性,该属性名称必须有一个数字。

打印结果如下:

[{
    room[1]: 1
  },
  {
    room[2]: 2
  },
  {
    room[3]: 3
  },
  {
    room[4]: 4
  },
  {
    room[5]: 5
  },
  {
    room[6]: 6
  }
]

var = arr[]
for (let index = 0; index < 10; index++) {
  arr.push({
    `room[${index}]`: index,
  })
}
console.log(arr)

查看更多

查看更多

提问者
wen tian
被浏览
25
Ele 2019-07-03 21:27

缺少所谓的计算属性名称

假设变量声明中有错字 arr

var arr = [];
for (let index = 0; index < 10; index++) {
  arr.push({
    [`room[${index}]`]/*Computed-property names*/: index,
  });
}
console.log(arr)
.as-console-wrapper { min-height: 100%; }