JavaScript - Arrays - fill

javascript-arrays

// Array.prototype.fill():
The fill() method fills all the elements of an array from a start index to an 
end index with a static value.

arr.fill(value)
arr.fill(value, start)
arr.fill(value, start, end)

var numbers = [1, 2, 3]
numbers.fill(1);
// results in [1, 1, 1]

The fill method takes up to three arguments value, start and end. The start and 
end arguments are optional with default values of 0 and the length of the this 
object. If start is negative, it is treated as length+start where length is the 
length of the array. If end is negative, it is treated as length+end.

The fill function is intentionally generic, it does not require that its this 
value be an Array object.  The fill method is a mutable method, it will change 
this object itself, and return it, not just return a copy of it.

[1, 2, 3].fill(4);               // [4, 4, 4]
[1, 2, 3].fill(4, 1);            // [1, 4, 4]
[1, 2, 3].fill(4, 1, 2);         // [1, 4, 3]
[1, 2, 3].fill(4, 1, 1);         // [1, 2, 3]
[1, 2, 3].fill(4, -3, -2);       // [4, 2, 3]
[1, 2, 3].fill(4, NaN, NaN);     // [1, 2, 3]
Array(3).fill(4);                // [4, 4, 4]
[].fill.call({ length: 3 }, 4);  // {0: 4, 1: 4, 2: 4, length: 3}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License