1 Overview
arr.fill() is a new method of ES6.
The fill() method is used to replace the elements of an array with a fixed value.
2 fill()
Syntax: array.fill(value, start, end)
parameters
- value is required. Filled value.
- start is optional. Start filling position.
- end is optional. Stop filling position (default is array.length)
filling starts from the start position and ends at the end-1 position, excluding the end position.
Modify the original array directly
3 example
let arr1 = [1, 2, 3, 4, 56, 7, 7, 8, 9];
arr1.fill(4, 2, 5);
console.log(arr1) // [1, 2, 4, 4, 4, 7, 7, 8, 9]
let arr2 = [1, 2, 3, 4, 56, 7, 7, 8, 9];
arr2.fill(4);
console.log(arr2) // [4, 4, 4, 4, 4, 4, 4, 4, 4]