gpt4 book ai didi

javascript - arr.forEach 未产生预期结果

转载 作者:行者123 更新时间:2023-12-01 02:21:03 26 4
gpt4 key购买 nike

我正在尝试填充使用 Array(5) 创建的数组每个元素的索引:

let arr = Array(5)

arr.forEach((item, index) => arr[index] = index)

console.log(arr)

// expected output:
// [0, 1, 2, 3, 4]

// instead I get
// [
// undefined,
// undefined,
// undefined,
// undefined,
// undefined
// ]

我哪里错了?

最佳答案

您需要用函数 .fill() 填充它

该数组实际上是空的,因此 forEach 不会迭代。

new Array(arrayLength)

arrayLength

If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with its length property set to that number (Note: this implies an array of arrayLength empty slots, not slots with actual undefined values). If the argument is any other number, a RangeError exception is thrown.

let arr = Array(5).fill();
arr.forEach((item, index) => { arr[index] = index })
console.log(arr);

Why does my code work when I change the first line to let arr = [...Array(5)]?

let arr = Array(5); 
Array.from(arr) // equals to [...arr];

.apply 将省略的元素“扩展”为适当的参数,结果最终类似于 Array(undefined, undefined, undefined, undefined, undefined) Reference

关于javascript - arr.forEach 未产生预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49213723/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com