美文网首页
使用生成器来实现斐波那契数列

使用生成器来实现斐波那契数列

作者: 蜗牛Coming | 来源:发表于2019-07-25 10:24 被阅读0次
function *feb(max){
var count = 0,current = 1,last = 0;
while(max>count++){
  yield current;
  var temp = current;
  current += last;
  last = temp;
}
}
var o = feb(10),res,result= [];
while(!(res = o.next()).done){
  result.push(res.value);
}
console.log(result);

生成器函数通常和 yield 关键字同时使用。函数执行到每个 yield 时都会中断并返回 yield 的右值(通过 next 方法返回对象中的 value 字段)。下次调用 next,函数会从 yield 的下一个语句继续执行。等到整个函数执行完,next 方法返回的 done 字段会变成 true。

摘抄:https://imququ.com/post/generator-function-in-es6.html

相关文章

网友评论

      本文标题:使用生成器来实现斐波那契数列

      本文链接:https://www.haomeiwen.com/subject/nyecrctx.html