-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;
}
2

2 Answers 2

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)),
    )
}
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));

1
  • 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
    Commented Nov 11, 2022 at 18:03

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.