了解 JavaScript 中的生成器

Understanding generators in JavaScript

有人可以帮助我理解以下代码的作用吗?为什么 "one" 没有打印到控制台?另外,g 是生成器还是 go 生成器?

function *go() {
  var foo = yield;
  console.log(foo);
}

var g = go();
console.log(g.next('one')); 
console.log(g.next('two')); 

输出:

Object {value: undefined, done: false}
two
Object {value: undefined, done: true}

第一行是yield的对象结果。该值未定义,因为您在 yield 关键字后没有任何内容,但函数未完成。

这两个是函数中的log函数打印出来的

第三行是函数结束的结果,值仍未定义(没有return语句或值),函数完成。

Why is "one" not printed to the console?

因为第一个 .next() 调用(通常没有参数)只会将生成器从函数体代码的开头推进到第一个 yield 表达式(和 returns那里产生的价值)。 "passed in" 的值无法在任何地方访问。

只有第二个 .next(…) 调用然后提供来自 yield 表达式的值,将生成器状态继续到下一个 yield 或函数结束。

Also, is g the generator or is go the generator?

ggenerator(也是 iterator)。 go 是一个 生成器函数 ,它创建生成器(就像构造函数创建实例)。

只是为了添加到讨论中。这是一个演示,展示了我认为你想要实现的目标。引用自Mozilla docs

Calling a generator function does not execute its body immediately; an iterator object for the function is returned instead. When the iterator's next() method is called, the generator function's body is executed until the first yield expression, which specifies the value to be returned from the iterator or, with yield*, delegates to another generator function. The next() method returns an object with a value property containing the yielded value and a done property which indicates whether the generator has yielded its last value.

function* go(values) {
  while (values.length) {
    yield values.shift();
  }
}

var g = go(['one', 'two']);
document.getElementById("output").innerHTML += JSON.stringify(g.next());
document.getElementById("output").innerHTML += JSON.stringify(g.next());
// I'm done!
document.getElementById("output").innerHTML += JSON.stringify(g.next());
<pre id="output"></pre>