fill

.fill( val )

Fill will replace all values in this array with the value given. All values are replaced, and this array is then returned to allow method chaining.

ns = [ 1, 2, 3, 4, 5 ]
ns.fill( 6 )

// prints out [ 6, 6, 6, 6, 6 ]
console( ns )

.fill( numElements, val )

This is the same as the standard fill, however giving it a number of elements allows you to set that number of elements of the value given. This will fill from the start of the array, and if the length is bigger then the amount given, then it's size is increased.

// sets ns to [ "foobar", "foobar", "foobar", "foobar", "foobar" ]
ns = [].fill( 5, "foobar" )

You can also pass in a negative size to change those items at the end of an array.

.fill( startIndex, numElements, val )

Just like the previous fill method, however this allows you to set a starting index. It will fill 'numElements' number of items, with the value given, from that point on.

ns = [ 1, 2, 3, 4, 5, 6 ]
// changes ns to [1, 2, null, null, null, 6]
ns.fill( 2, 3, null )

You can also pass in a negative index to start filling backwards from the end of the array. So -1 is the last element, -2 is the penultimate element, and so on,

Note that if you use a negative starting index, but the number of elements is greater then those left in the array, then this will pad out the array with the value given rather than wrapping around to the beginning.

For example 'ns.fill( -2, 5, :blah )' will change the last 2 items, and add on 3 more to the end.

See also

map