I've been trying to create a Fibonacci sequence that always starts with [0, 1] using simple JS. However, the way it's written now, the function does not return the first two items in an array when I call the corresponding n number. So, for n = 1 and n = 2 (and ONLY those values of n), I get undefined when calling the function. However, whenever I call n larger than 2, the Fibonacci sequence returns correctly, with the correct amount of array items (so, including items 0 and 1, which I am unable to call on their own).
Here is the code:
function generator(n) {
var output = [];
var num1 = 0;
var num2 = 1;
var next;
if (n === 1) {
output = [0];
} else if (n === 2) {
output = [0, 1];
} else {
output = [num1, num2];
for (var count = 2; count < n; count++) {
next = num1 + num2;
num1 = num2;
num2 = next;
output.push(next);
}
return output;
}
}
Would anyone know what is wrong in the code? Thanks so much for any help!
Aucun commentaire:
Enregistrer un commentaire