6

如果你有类似的发电机,

function* f () {
  // Before stuff.
  let a = yield 1;
  let b = yield 2;
  return [a,b];
}

然后运行

var g = f();
// this question is over this value.
g.next(123); // returns: { value: 1, done: false }
g.next(456); // returns: { value: 2, done: false }
g.next(); // returns: { value: [ 456, undefined ], done: true }

第一次调用.next()set ato123和第二次调用 set bto 456,但是最后一次调用.next()this 是 return,

{ value: [ 456, undefined ], done: true }

难道第一次调用中的参数g.next就迷路了?他们会发生什么?使用上面的例子,我该如何设置a

4

3 回答 3

4

尝试:

var g = f();
// this question is over this value.
g.next(); // returns: { value: 1, done: false }
g.next(123); // returns: { value: 2, done: false }
g.next(456); // returns: { value: [123, 456], done: true }
于 2014-01-22T03:06:25.767 回答
2

传递给第一个 'next()' 调用的值将被忽略。查看此ES6 TDD Coding Kata的最后一个测试(第 34 行)

对于那些对如何设置a&感到困惑的人,查看迭代器和生成器b的“高级生成器”部分可能是个好主意

于 2015-07-16T15:10:15.387 回答
1

来自 MDN迭代器和生成器

传递给 next() 的值将被视为暂停生成器的最后一个 yield 表达式的结果。

答案:

第一次调用 g.next 的参数会丢失吗?

由于第一次调用没有last yield expression that paused the generator,这个值基本上被忽略了。您可以在ECMAScript 2015 语言规范中阅读更多内容。

他们会发生什么?

在随后调用next()传递的值时,将用作the return value of the last yield expression that paused the generator.

使用上面的例子,我该如何设置?

您可以按照LJHarb 的建议进行操作。

"use strict";

let f = function*() {
	let a = yield 1;
	let b = yield 2;
	return [a, b];
};

let g = f();

document.querySelector("#log_1").innerHTML = JSON.stringify(g.next());
document.querySelector("#log_2").innerHTML = JSON.stringify(g.next(123));
document.querySelector("#log_3").innerHTML = JSON.stringify(g.next(456));
<div id="log_1"></div>
<div id="log_2"></div>
<div id="log_3"></div>

于 2016-02-16T23:10:31.613 回答