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