Generate and fill a new array `fill()`
Generate and fill a new array fill()
The fill()
method sets a specific value to the elements of the array.
If you have an array with some values:
and you want to replace/fill the elements with the value 0
, you can call fill()
method on the array, using 0
as a parameter:
As you can see the fill()
method changes the content of the original array. The size of the array will be the same as the original one.
The fill()
method has two more optional parameters about the starting index to apply the changes and the ending index.
For example, if you want to replace values starting with the second element (remember 0 index array):
you can also set the last index to apply the replacement. For example, if you want to replace elements from index 1 (the second element) until index 3 (the third element included):
If you want to fill/replace the last element you can use the negative index: