Question:
I am fibSeq = [0,1]
to make a loop that adds to the fibSeq = [0,1]
array 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)
Y results in fibSeq = [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 strange numbers, not the ones I want (the ones I want are fibonacci): [0, 1, 1, 3, 5, 7, 9, 11]
I would appreciate an explanation of why the loop is not updated instead of a solution on how to obtain the fibonacci numbers since I am doing this to learn JS and I try to avoid complete solutions because otherwise I will not learn. Thank you.
Answer:
The problem is in the first lines:
var elultimo = fibSeq.length -1
var elanterior = elultimo - 1
Because the value 0
and the value 1
and they are "pushed" as many times as num
, since it is done outside the loop, in addition to the fact that you have the length
value, not the value that occupies that position in the loop.
The most direct solution and without modifying the original code much is, precisely, accessing the values of the array and adding them:
function fib(num){
var fibSeq = [0,1];
for (var i = 0; i < num; i++){
var length = fibSeq.length;
var last = fibSeq[length-1];
var prevLast = fibSeq[length-2];
var suma = last + prevLast;
fibSeq.push(suma)
}
return fibSeq
}
console.log(fib(6));
A certain improvement that I propose is to use the syntax of the latest version of Javascript, ES6:
function fib(num){
let fibSeq = [0,1];
for (let i = 0; i < num; i++){
const length = fibSeq.length,
last = fibSeq[length-1],
prevLast = fibSeq[length-2],
suma = last + prevLast;
fibSeq.push(suma)
}
return fibSeq
}
console.log(fib(6));