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;
}
CodePudding user response:
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));
CodePudding user response:
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)),
)
}