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