When you talk about code, you make the transition from fib[3] = fib[2] + fib[1] to fib[3] = fib[3] . This occurs as a transformation that leads to a correct statement, but it is not how it works. This code adds the value at index 2 to the value at index 1 . This is not the same as taking a value in index 3 . The way this reasoning should work is as follows:
You start with fib = [0, 1] . Then in the first iteration of the loop you have fib[2] = fib[1] + fib[0] . This means that you add the value at index 0 (which happens to be 0 ) to the value at index 1 (which happens to be 1 ) to get the value that you put at the end of array ( 1 ). Then in the second iteration, you do a similar thing, adding the value in index 1 (another 1 ) to the value in index 2 (also 1 ) to get 2 , which goes to the end of the array. This continues, and at each iteration, you add the last two values โโto the array to get the next value.
In JavaScript, when an array of type fib , fib[i] refers to the i th value in this array, starting from 0 . So fib[0] is the first element in the array, fib[1] is the second element in the array, etc.
murgatroid99
source share