代码之家  ›  专栏  ›  技术社区  ›  Billal Begueradj

Javascript:使用循环变量值作为对象的键[duplicate]

  •  2
  • Billal Begueradj  · 技术社区  · 6 年前

    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

    如何做到这一点?

    2 回复  |  直到 6 年前
        1
  •  2
  •   Nina Scholz    6 年前

    你可以用 Array.from 用一个带 computed property name .

    var array = Array.from({ length: 2 }, (_, i) => ({ [i]: i + 1 }));
    
    console.log(array);
        2
  •  2
  •   Mark Baijens    6 年前

    let arr = []
    for(let i=0; i<2; i++) {
      arr.push({
        [i]: i+1
      })
    }
    console.log(arr)