0

I am trying to create a function that takes in two vairables a and b, this function will create an array with variable a reapeated b times.

This is how far I have gone but It's not outputting th correct number of items in the array:

var createArr = function(a, b) {
    // returns an array with variable a repeated b times.
    if (typeof b == 'number') {
      var arr = [];

      for (var i = 0; i <= b; i++) {
        arr.push(a);
      };
    }
      return arr;
    };
    
 createArr("ready",3)

3 Answers3

2

Easy:

function createArr(a, b) {
    return Array(b).fill(a);
}
Robo Robok
  • 21,132
  • 17
  • 68
  • 126
  • 2
    @RoboRobok You might want to check out [why we mark questions as duplicates](https://stackoverflow.com/help/duplicates) in the first place. We're not here to be a helpdesk and grab some internet points. We're here to make a library of high quality Q&A's that can be used by people beyond the person asking. Marking questions as duplicates helps to reach that goal by keeping the high-quality and up-to-date answers in one place. (Also, two wrongs don't make a right. Answering duplicates because others also do it doesn't justify it.) – Ivar May 23 '20 at 18:05
1

If you use <= and the value “3” for “b”, the loop will run once for 0, 1, 2, and 3. Oops, that’s 4 times.

Instead you want to use < so the loop will run once for 0, 1, then 2, and not for 3.

See also https://en.wikipedia.org/wiki/Fencepost_error

Rikki Gibson
  • 4,136
  • 23
  • 34
0

for loop, break will be < not <= because when <= for loop start with 0 and break when it 3 so loop 4 times when need to loop 3 times so need an use <

var createArr = function(a, b) {
    // returns an array with variable a repeated b times.
    if (typeof b == 'number') {
      var arr = [];

      for (var i = 0; i < b; i++) {
        arr.push(a);
      };
    }
      return arr;
    };
    
 console.log(createArr("ready",3));
Mohammad Ali Rony
  • 4,695
  • 3
  • 19
  • 33