让我们简化我的问题;我有这段代码:
let arr = []
for (let i = 0; i < 2; i++) {
arr.push({
i: i + 1
})
}
console.log(arr)
输出:Array [Object { i: 1 }, Object { i: 2 }]
但我想要:Array [Object { 0: 1 }, Object { 1: 2 }] // Values of 'i' as object keys
如何实现这一目标?
最佳答案
您可以使用Array.from
并对带有 computed property name 的对象进行单个循环.
var array = Array.from({ length: 2 }, (_, i) => ({ [i]: i + 1 }));
console.log(array);
关于Javascript:使用循环变量值作为对象的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52699441/