- Learning JavaScript Data Structures and Algorithms
- Loiane Groner
- 176字
- 2021-08-27 18:41:18
Using the fill method
The fill method fills the array with a value. For example, consider the following array:
let numbersCopy = Array.of(1,2,3,4,5,6);
The numbersCopy array has the length 6, meaning we have six positions. Let's use the following code:
numbersCopy.fill(0);
Here, the numbersCopy array will have all its positions with value ([0,0,0,0,0,0]). We can also pass the start index that we want to fill the array with, as follows:
numbersCopy.fill(2, 1);
In the preceding example, all the positions of the array will have the value 2, starting from position 1 ([0,2,2,2,2,2]).
It is also possible to pass the end index that we want to fill the array with:
numbersCopy.fill(1, 3, 5);
In the preceding example, we will fill the array with value 1 from index 3 to 5 (not inclusive), resulting in the following array: [0,2,2,1,1,2].
The fill method is great when we want to create an array and initialize its values, as demonstrated:
let ones = Array(6).fill(1);
The preceding code will create an array of length 6 and all its values as 1 ([1,1,1,1,1,1]).