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.
The problem is in the first lines:
Because the value
0
and the value1
are taken and "pushed" as many times asnum
, since it is done outside the loop, plus you have the value oflength
the value that occupies that position of the loop.The most direct solution and without modifying the original code much is precisely to access the values of the array and add them:
A certain improvement that I propose is to use syntax from the latest version of Javascript, ES6:
An alternative proposal, using fewer variables:
And another possible answer: