-2

Can someome explain to me how New Array, and Array works with this loop? Also, anyone knows if is possible of doing a array and inside this array a function? Because this way of doing seem kinda wrong considering POO and SRP Here`s the link of the exercise: https://www.codewars.com/kata/569e09850a8e371ab200000b/train/javascript

function preFizz(n) {
  let output = new Array();
  let num = 1;
  while(output.length  < n){
    output.push(num);
    num += 1;
  }
  return output;
}
Davi
  • 17
  • 5

2 Answers2

1

Ok, i found the answer thanks to epascarello and Abdennour TOUMI. Here´s the link where of the answer: How to create an array containing 1...N

Basically i was trying to finding more about arrays and loops(In a more pratice way), this codes maked more easier to understand

let demo = (N,f) => {
    console.log(
        Array.from(Array(N), (_, i) => f(i)),
    )
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
Davi
  • 17
  • 5
0

Why not use a traditional for-loop? It has declaration, conditional, and increment functionality built right in.

const preFizz = (n) => {
  const output = [];
  for (let num = 1; num <= n; num++) {
     output.push(num);
  }
  return output;
}

console.log(...preFizz(10));

A more modern version of this would be to declare an array of a specified length and map the indices.

const preFizz = (n) => Array.from({ length: n }).map((_, i) => i + 1);

console.log(...preFizz(10));
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • The asker already posted an answer with the "modern version" 10 minutes ago, and using the callback argument of `Array.from` which is the better way to use it. Using `map` means there is an extra array created in the process. – trincot Nov 11 '22 at 18:03