The Fibonacci sequence is: 1 1 2 3 5 8 ..., the following number is the first two digits of the and, and the second number is 1, with JS implementation
Two methods, one through the common recursive call, the second not through recursion, but through a powerful closure implementation.
1. Recursive implementations
// Fab 1 1 2 3 5 8 function Fab (num) { if(num==1 | | num==2) { return 1; } Else { return Fab (num-1) +fab (num-2); } } Alert (Fab (5))
2. Closure implementation. Closures are mainly: 1. Simulating object-oriented encapsulation data 2. Save the data, because if you define i,j outside the function, it will become a global variable, unsafe, because it will be called to modify, and
Closures can be a good package of data, without recursion can achieve the same function, more commonly used.
//Closures1. Simulating object-oriented encapsulation data 2. Saving Data varFIB = (function () { vari = 1; varj = 1; return function(n) {varres =J; for(varK = 3; K <= N; k++) {res= i +J; I=J; J=Res; } returnRes; } })(); document.write (FIB (5));
Two common methods of JS realizing Fibonacci-cut sequence