ES6中的生成器

时间:2017-11-02 11:42:05

标签: javascript ecmascript-6 generator

我创建了一个使用es6生成器生成斐波那契序列的函数:

//WARNING CAUSES INFINITE LOOP
function* fibonacci(limit = Infinity) {
  let current = 0
  let next = 1

  while (current < limit) {
    yield current
      [current, next] = [next, current + next]
  }
}

for (let n of fibonacci(200)) {
  console.log(n)
}

上述功能不会交换这两个数字,而如果在任何其他功能中正常完成,则交换这两个数字。在运行此函数时,我得到一个无限循环。 为什么变量交换不起作用?

2 个答案:

答案 0 :(得分:2)

您遇到了语法错误:缺少分号会使引擎将您的语句解析为

yield (current [ current, next ] = [ next, current + next ])
//             ^        ^
// property access    comma operator

如果您想省略分号,let them be automatically inserted需要可能的,那么( [开头的每一行都会need to put one at the begin },/+-`

function* fibonacci(limit = Infinity) {
  let current = 0
  let next = 1

  while (current < limit) {
    yield current
    ;[current, next] = [next, current + next]
  }
}

for (let n of fibonacci(200)) {
  console.log(n)
}

答案 1 :(得分:-1)

你必须首先交换然后屈服。 Yield会将控制权交还给调用者,因此该方法会停止在那里执行..

这将有效(在Firefox中测试

function* fibonacci(limit = Infinity) {
  let current = 0
  let next = 1

  while (current < limit) {
    [current, next] = [next, current + next];
    yield current;

  }
}

for (let n of fibonacci(200)) {
  console.log(n)
}