js array fill
时间: 2023-09-29 13:02:53 浏览: 48
The JavaScript array fill() method is used to fill an array with a static value, replacing all the existing elements with the specified value. This method modifies the original array and returns the modified array.
Syntax:
```
array.fill(value, start, end)
```
Parameters:
- value: The value to fill the array with.
- start (optional): The index to start filling the values from. Defaults to 0 if not provided.
- end (optional): The index to stop filling the values at. The end index is not included. Defaults to the length of the array if not provided.
Example:
```
let arr = [1, 2, 3, 4, 5];
arr.fill(0, 2, 4);
console.log(arr); // Output: [1, 2, 0, 0, 5]
```
In the above example, the fill() method is used to replace the values at the 2nd and 3rd index with 0. The start index is 2 and the end index is 4 (which is not included), so the values at the 2nd and 3rd index are replaced with 0.