简体   繁体   English

ES6中的生成器

[英]Generators in ES6

I have created a function to generate fibonacci series using es6 generators: 我创建了一个使用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)
}

The above function doesn't swap the two numbers while if done normally in any other function swaps the two. 上面的函数不会交换两个数字,而如果在其他函数中正常完成交换,则会交换两个数字。 On running this function I get an infinite loop. 运行此函数时,我会遇到无限循环。 Why doesn't the variable swap work? 为什么变量交换不起作用?

You've got a syntax mistake: a missing semicolon makes the engine parse your statement as 您有一个语法错误:缺少分号会使引擎将您的语句解析为

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

If you want to omit semicolons and let them be automatically inserted where ever possible needed, you will need to put one at the begin of every line that starts with ( , [ , / , + , - or ` : 如果你想省略分号,并让他们自动插入需要的地方有可能 ,您将需要把一个在开始每一个开头线([/+-`

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)
}

You have to first swap and then yield. 您必须先交换然后屈服。 Yield will give control back to the caller, so the method kindad stops executing there.. Yield将控制权交还给调用方,因此kindad方法将在此处停止执行。

This will work (tested in Firefox 这将起作用(在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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM