ES6中的生成器:嵌套yield?

3
有人能解释一下这段代码是如何工作的吗?(嵌套yield):
function* anotherGenerator(i) {
  yield i + 1;
  yield i + 2;
  yield i + 3;
}

function* generator(i){
  yield i;
  yield* anotherGenerator(i);
  yield i + 10;
}

var gen = generator(10);

console.log(gen.next().value); // 10
console.log(gen.next().value); // 11
console.log(gen.next().value); // 12
console.log(gen.next().value); // 13
console.log(gen.next().value); // 20

在第一次使用console.log()时我们得到了一个值为10,之后是11、12、13、20......这个嵌套的yield是如何工作的呢?


2
这是来自MDN的一个例子,对吧?那个页面链接到描述yield*的页面。 - undefined
1个回答

16

yield* anotherGenerator(i);基本上是一个方便的缩写,代表着

for (var value of anotherGenerator(i)) {
  yield value;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接