简体   繁体   中英

What are the steps used in this function used to calculate the Fibonacci sequence?

 let a = 0; let b = 1; for (let i = 1; i <= 10; i++) { var c = a + b; a = b; b = c; console.log(c); }

So I have this little code that apparently works and that gives the sequence of Fibonacci but I still don't understand how the code does its thing so I think need a visual representation with numbers to understand.

Work through it step-by-step:

let a = 0;
let b = 1;

Self-explanatory variable assignment.

for (let i = 1; i <= 10; i++) {...}

Iterate from 1 to 10 with i storing the current iteration

var c = a + b;

Make a variable c set to a + b .

a = b;
b = c;

Set a to b and b to c - makes new base values for next iteration.

This example shows all the variables:

 let a = 0; let b = 1; for (let i = 1; i <= 10; i++) { var c = a + b; a = b; b = c; console.log(`a: ${a}, b: ${b}, c: ${c}, i: ${i}`); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM