JavaScript: Array.prototype.fill
New in JS2015.
arrayX.fill(value)
-
Replace all elements by value. Return the modified arrayX.
const xx = [0, 1, 2]; console.log(xx.fill(7)); // [ 7, 7, 7 ] console.log(xx); // [ 7, 7, 7 ]
use with Array Constructor
const xx = Array(4).fill(0); console.log(xx); // [ 0, 0, 0, 0 ]
arrayX.fill(value, start_index)
-
Replace start from start_index
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, start_index, end_index)
-
Replace up to end_index, 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 ]