0

I am trying to use the following prototype to fill an empty array with integers from 1-100. As per MDN's documentation:

array.prototype.fill(value, [optional start & end index])

If my understanding is correct if I call my value = 1 then if I say:

[5].fill(1); I would be left with an array with 1 sitting at all 5 index points of the array. Is there a way using .fill() to say value = 1...100? I'm beginning to think running a for loop to push values 1 - 100 might be the only way to do this, but I thought I would see if this method worked the same.

rockchalkwushock
  • 1,143
  • 2
  • 9
  • 19

2 Answers2

1

No, fill method, doesn't take a function or an iterator as an argument to change the static value with every iteration.

try this approach

    var N = 100;
    var arr = Array.apply(null, {length: N+1}).map(Number.call, Number);
    arr.splice(0,1); 

console.log(arr);

splice at the end removes the first item of the array which was 0.

If you don't want to do splice

        var N = 100;
        var arr = Array.apply(null, {length:  N}).map(Number.call, function(item, index){ return item + 1 });

    console.log(arr);

Some other good approaches are mentioned in this answer to fill values dynamically.

Community
  • 1
  • 1
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

The fill() method fills all the elements of an array from a start index to an end index with a static value.

Therefore, it will not be possible to increment this value using the fill() method.

Gavin
  • 4,365
  • 1
  • 18
  • 27