You need to fill it with function .fill()
That array is actually empty, so the forEach
doesn't iterate.
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
"expands" the elided elements into proper arguments, and the results ends up being something like Array(undefined, undefined, undefined, undefined, undefined) Reference