Skip to content
Advertisements

Array fill()

The fill() method serves to fill the array with the specified variables. it takes 3 parameters. They are value, start and end. Start and end values ​​can be given on request. But it is imperative to enter value.

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.

fill () changes the structure of the array. ( it doesn’t just leave values ​​like every )

 array.fill(value, start, end) 

value :(Required) The value to fill the array.
start :(Optional) The index to start the array (default index is 0)
end :(Optional)   The index to stop filling the array (default is array.length)

        var list = [1, 2, 3, 4, 5, 6];
        console.log(list.fill(9, 1, 3))
        console.log(list.fill(9, 3, 6))
        console.log(list.fill(9, 2))
        console.log(list.fill(9))

output:

[1, 9, 9, 4, 5, 6]
[1, 9, 9, 9, 9, 9]
[1, 9, 9, 9, 9, 9]
[9, 9, 9, 9, 9, 9]


Examples

Example 1 (negative value)

        let list1 = [2, 4, 6].fill(0, -3, -2)
        let list2 = [1,2,3].fill(0,-2,-1)
        console.log(list1)
        console.log(list2)

output:

[0, 4, 6]
[1, 0, 3]


Example 2 (worthless element)

        let list = [1, 2, 3].fill(2, NaN, NaN)
        console.log(list)

output:

[1, 2, 3]


Example 3

console.log(Array(5).fill("*"))

output:

[ * , * , * , * , * ]



Array fill() Polyfill

if (!Array.prototype.fill) {
  Object.defineProperty(Array.prototype, 'fill', {
    value: function(value) {

      if (this == null) {
        throw new TypeError('this is null or not defined');
      }

      var O = Object(this);

      var len = O.length >>> 0;

      var start = arguments[1];
      var relativeStart = start >> 0;

      var k = relativeStart < 0 ?
        Math.max(len + relativeStart, 0) :
        Math.min(relativeStart, len);

      var end = arguments[2];
      var relativeEnd = end === undefined ?
        len : end >> 0;

      var final = relativeEnd < 0 ?
        Math.max(len + relativeEnd, 0) :
        Math.min(relativeEnd, len);

      while (k < final) {
        O[k] = value;
        k++;
      }

      return O;
    }
  });
}

Advertisements

2 Comments »

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: