I'm studying and making exercise of the Fibonacci sequence and I don't understand where is the "i" value goes to?
function fibonacciGenerator (n) {
var output = [];
if (n === 1) {
output = [0];
}
else if (n === 2) {
output = [0, 1];
}
else if (n === 0) {
output = ["Please put in the number"];
}
else {
output = [0, 1];
for (var i = 2; i < n; i++) {
output.push(output[output.length - 2] + output[output.length - 1]);
}
}
return output;
console.log(output);
}
So the problem line was this loop
else {
output = [0, 1];
for (var i = 2; i < n; i++) {
output.push(output[output.length - 2] + output[output.length - 1]);
}
so the code just understand by itself that output that are next to [0,1,...] is "i" right? Why can't i just put this line like this
else {
output = [0, 1];
for (var n = 2; n < output.length; n++) {
output.push(output[output.length - 2] + output[output.length - 1]);
}
(BTW It said "Uncaught ReferenceError: i is not defined")
will not work because the for-loop condition depends on the array length's (
n < output.length) and you are modifying the array length's inside the loop.For a for-loop, you should use 'let' instead of 'var', like this
Check this stackoverflow post that explains in detail the difference between
varandlet