r/code • • 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

3 comments sorted by

View all comments

Show parent comment

1

u/lgastako Mar 28 '24

The first reference to output is output[index1] which references the element of output at index1 and the second reference to output is output[index2] which references the element of output at index2.