I try to make a loop that adds to the array fibSeq = [0,1]
the sum of the two previous numbers.
That is, the result with 6 iterations should be this:fibSeq = [0,1,1,2,3,5,8,13]
However mine does not update:
function fib(num){
var fibSeq = [0,1];
var elultimo = fibSeq.length -1
var elanterior = elultimo - 1
var suma = elultimo + elanterior
for (var i = 0; i < num; i++){
fibSeq.push(suma)
}
return fibSeq
}
fib(6)
And it resultsfibSeq = [0,1,1,1,1,1,1]
I have tried to include the statements inside the loop
function fib(num){
var fibSeq = [0,1];
var elultimo = fibSeq.length -1
var elanterior = elultimo - 1
var suma = elultimo + elanterior
for (var i = 0; i < num; i++){
elultimo = fibSeq.length -1
elanterior = elultimo - 1
suma = elultimo + elanterior
fibSeq.push(suma)
}
return fibSeq
}
fib(6)
But then it gives me some weird numbers, not the ones I want (the ones I want are the fibonacci numbers):[0, 1, 1, 3, 5, 7, 9, 11]
I would appreciate an explanation of why the loop does not update instead of a solution on how to get the fibonacci numbers since I'm doing this to learn JS and I try to avoid complete solutions because otherwise I don't learn. Thanks.