Fibonacci: Starting with 0 and 1, each term in the Fibonacci sequence is equal to the sum of the first two. Examples of Fibonacci numbers: 1, 1, 2, 3, 5, 8, 13, 21, 34
1, find the Fibonacci number of the NTH term, that is, add the first two terms of the n term, the first term is N-1, the first two terms are n-2. 2. The NTH Fibonacci number is (n-1) + (n-2), so we can use recursion. 3. What is recursion? Recursion is a function calling itself. Arguments.callee (); arguments.callee (); PS: arguments is a class array object that contains all the arguments passed to the function. Arguments has a property called callee, which is a pointer to the function that has this arguments object.)
Now look at the code for the first method:
function fibonacci(n) {
/* The first two terms of the Fibonacci sequence are both 1, so determine if n is equal to 1 or 2. If so, return 1 */
n = n && parseInt(n);
if (n == 1 || n == 2) {
return 1;
};
// Use arguments.callee for recursion
return arguments.callee(n - 2) + arguments.callee(n - 1);
}
let sum = fibonacci(8)
console.log(sum) / / 21
Copy the code
We used recursion to output the NTH Fibonacci number, but recursion is a waste of browser resources. If the NTH number is too large, it will run much faster, so we optimized it with a for loop.
The second method:
function fibonacci(nub) {
let n = nub && parseInt(nub);
let n1 = 1; // The initial value of n = 1 is 1
let n2 = 1; // The initial value of n = 2 is 1
let f; // Declare the variable sum to accept the NTH Fibonacci number
Return 1 if n = 1 or n = 2
if(n == 1 || n == 2) {
return 1;
}
for(let i = 2; i < n; i++) {
f = n1 + n2;
n1 = n2;
n2 = f;
}
return f
}
let sum = fibonacci(8)
console.log(8) / / 21
Copy the code
The third method:
function fibonacci(n) {
n = n && parseInt(n);
let n1 = 1;
let n2 = 1;
Return 1 if n = 1 or n = 2
if(n == 1 || n == 2) {
return 1;
}
// Using destruct assignment, n1 equals n2, n2 equals n1 + n2 returns n2
for (let i = 2; i < n; i++) {
[n1, n2] = [n2, n1 + n2]
}
return n2
}
Copy the code