JavaScript生成斐波那契数列
Posted LightSong@计海拾贝
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript生成斐波那契数列相关的知识,希望对你有一定的参考价值。
常规写法
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(" "));
以上是关于JavaScript生成斐波那契数列的主要内容,如果未能解决你的问题,请参考以下文章