To set all values of an array with JavaScript, we can use the fill
method
For instance, we can write:
const arr = [...Array(20)].fill(10)
console.log(arr)
We create an array with 20 empty slots with Array(20)
.
Then we spread that into a new array to create an array with 20 undefined
entries.
Next, we call fill
with 10 to replace will the undefined
values with 10.
Therefore, arr
is:
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
as a result.