JS: Array.prototype.fill
New in JS2015.
arrayX.fill(value)
-
- Modify the array by giving a value to all indexes, including missing indexes in Sparse Array.
- Return the modified arrayX.
// using fill to fill sparse array const xx = []; xx.length = 4; xx.fill(0); console.log(xx); // [ 0, 0, 0, 0 ]
// using fill to change all values of a normal array const xx = [0, 1, 2]; console.log(xx.fill(7)); // [ 7, 7, 7 ] console.log(xx); // [ 7, 7, 7 ]
arrayX.fill(value, startIndex)
-
Fill start from startIndex
console.log([0, 1, 2, 3].fill(9, 0)); // [ 9, 9, 9, 9 ] console.log([0, 1, 2, 3].fill(9, 1)); // [ 0, 9, 9, 9 ] console.log([0, 1, 2, 3].fill(9, 2)); // [ 0, 1, 9, 9 ] console.log([0, 1, 2, 3].fill(9, 3)); // [ 0, 1, 2, 9 ] console.log([0, 1, 2, 3].fill(9, 4)); // [ 0, 1, 2, 3 ]
arrayX.fill(value, startIndex, endIndex)
-
Replace up to endIndex, not including it.
console.log([0, 1, 2, 3].fill(9, 0, 0)); // [ 0, 1, 2, 3 ] console.log([0, 1, 2, 3].fill(9, 0, 1)); // [ 9, 1, 2, 3 ] console.log([0, 1, 2, 3].fill(9, 0, 2)); // [ 9, 9, 2, 3 ] console.log([0, 1, 2, 3].fill(9, 0, 3)); // [ 9, 9, 9, 3 ] console.log([0, 1, 2, 3].fill(9, 0, 4)); // [ 9, 9, 9, 9 ]