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); //
console.log(gen.next().value); //
console.log(gen.next().value); //
// ...

生成器函数+斐波那契数列

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:\n" + arr.join("\n"));
上一篇:jdk新特性


下一篇:【转载】salesforce 零基础开发入门学习(五)异步进程介绍与数据批处理Batchable