【问题标题】:Create Array and fill with index plus one in JavaScript [duplicate]在JavaScript中创建数组并用索引加一填充[重复]
【发布时间】:2020-10-26 15:51:55
【问题描述】:

我正在尝试使用 new Array() 创建一个数组并填充索引 + 1 但不知何故,虽然数组创建成功但值未正确填充。

代码 -

var aa = (new Array(4)).map((x, index) => {
    return index + 1;
});

console.log(aa);

输出 - [undefined, undefined, undefined, undefined]

预期 - [1, 2, 3, 4]

让我知道我在这里做错了什么。

【问题讨论】:

  • 谢谢@adiga。我知道它会在那里,只是找不到。

标签: javascript arrays reactjs ecmascript-6


【解决方案1】:

map 只访问实际存在的条目,它会跳过稀疏数组中的间隙。

有多种方法可以做到这一点:

  1. 您可以使用Array.from 及其映射回调:

    const as = Array.from(Array(4), (_, index) => index + 1);
    
    console.log(as);
  2. 您可以使用简单的for 循环:

    const as = [];
    for (let index = 1; index <= 4; ++index) {
        as.push(index);
    }
    
    console.log(as);
  3. 您可以使用fill,然后使用map

    const as = Array(4).fill().map((_, index) => index + 1);
    
    console.log(as);
  4. fill+map 的变体,您可以将 spread 用作Igor shows

【讨论】:

  • 回答反射。叹。我确定有一个 dup;etarget。标记为 CW 并关闭以找到它...
  • 为什么要映射一些你不需要的东西到Array(size + 1).fill().unshift()或者你可能喜欢拼接、切片等的任何其他方法。
  • @MarceDev - 用undefined 填充数组。 OP 想用索引 + 1 填充它。
【解决方案2】:
[...Array(4)].map((v, i) => i + 1)

【讨论】:

    猜你喜欢
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-15
    • 2017-03-22
    • 2021-04-16
    • 2020-03-14
    相关资源
    最近更新 更多