常规写法
https://cn.bing.com/search?q=js+fibonacci+sequence&pc=MOZI&form=MOZSBR
//Fibonacci function fibonacci(n) { var array = [0, 1]; for (var i = 2; i <= n; i++) { array.push(array[i - 1] + array[i - 2]); } return array[n]; } var n = 6; var ans = fibonacci(n); console.log(ans);
生成器
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator
function* idMaker() { var index = 0; while(true) yield index++; } var gen = idMaker(); // "Generator { }" console.log(gen.next().value); // 0 console.log(gen.next().value); // 1 console.log(gen.next().value); // 2 // ...
生成器函数+斐波那契数列
http://cwestblog.com/2011/07/28/javascript-fibonacci-generator-function-and-alternative/
function* fib() { var temp, num1 = 0, num2 = 1; while (1) { yield num1; temp = num1; num1 = num2; num2 += temp; } } // fibonacci generator function var genFib = fib(); // Print the first ten numbers in the fibonacci sequence. for (var arr = [], i = 0; i < 10; i++) { arr.push(genFib.next()); } alert("1st 10 fibonacci sequence numbers: " + arr.join(" "));