【问题标题】:generators in ES6: nested yields?ES6 中的生成器:嵌套产量?
【发布时间】:2017-03-06 13:01:54
【问题描述】:

谁能向我解释这段代码是如何工作的? (嵌套收益率):

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 是如何工作的?

【问题讨论】:

标签: ecmascript-6 generator


【解决方案1】:

yield* anotherGenerator(i); 基本上是

的方便简写
for (var value of anotherGenerator(i)) {
  yield value;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-18
    • 2012-06-27
    • 2018-05-16
    • 2018-04-14
    • 2020-06-06
    • 2011-09-19
    • 1970-01-01
    相关资源
    最近更新 更多