# 使用JavaScript ES6的新特性计算Fibonacci（非波拉契数列）

F(0)=1，F(1)=1, F(n)=F(n-1)+F(n-2)

```var fib = function (a, b) {

var _current = a + b;

return {

current: _current,

next: function () {

return fib(b, _current);

}
}
}```

```var generator = fib(1,1);

// 前一行调用fib(1,1)计算1+1的结果为2，将2存储到_current里通过current属性返回，所以打印2

// 同时返回next函数，函数体为return fib(b, _current); 此时b为1，_current为2

console.log(generator.current);

// 一旦执行next函数，则执行其指向的return fib(b, _current); 1 + 2 = 3

var result = generator.next();

console.log(result.current); // 打印3```

```var take = function(n, sequence) {

var result = [];

var temp = sequence;

for (var i = 0; i < n; i++) {

result.push(temp.current);

temp = temp.next();

}

return result;

}```

console.log(take(10, fib(1,1)));

# 采用ES6的GeneratorFunction生成非波拉契数列

```var fib_generator = function *(){

var current = 0, next = 1;

while(true) {

[next, current] = [next+current, next];

yield current;

}

}

var fib = fib_generator();

for(var i = 0; i < 10; i++){

console.log(fib.next().value);

}```

F(n)=F(n-1)+F(n-2)

```for(var i = 0; i < 10; i++){

var currentResult = fib.next();

console.log(currentResult.value);

}```

2689 篇文章64 人订阅

0 条评论