r/code • u/OsamuMidoriya • Mar 15 '24
Help Please Fibonacci Solution confirmation
in this project we want to make an array were the last 2 numbers equal the next
ex 0,1,1,2,3,5,8,13,21
in this code i is being push to the end of the array, i is starting out as 2
I know we use [] to access the arrays Ex output[0/2/3/5] for the index
why is output.length -1 inside of output[ ] when i first tried i did output[-1] but it didn't work
function fibonacciGenerator (n) {
var output = [];
if(n ===1){
output = [0];
}else if (n === 2){
output = [0, 1];
}else{
output =[0, 1];
for(var i = 2; i < n; i++){
output.push(output[output.length -1] + output[output.length -2]);
}
}
return output;
}
2
Upvotes
View all comments
Show parent comment
2
u/OsamuMidoriya Mar 27 '24
sorry for the late replay i was away.
how i have it is how the teacher explained it, the video is old maybe '18 or '19 so anything new that would make this easy is not taught. but i understand everything just not why we have output twice and the use of [ ]