小编Sat*_*rao的帖子

ES6生成器:首先调用next()

我试图了解如何使用ES6 Generator功能.除了这个关于在传递参数时进行空的next()函数调用的概念时,它似乎非常简单.这是我从Mozilla文档中引用的代码.

function* logGenerator() {
  console.log(yield);
  console.log(yield);
  console.log(yield);
}

var gen = logGenerator();

// the first call of next executes from the start of the function
// until the first yield statement

gen.next();
gen.next('pretzel'); // pretzel
gen.next('california'); // california
gen.next('mayonnaise'); // mayonnaise
Run Code Online (Sandbox Code Playgroud)

根据我的理解,代码只执行到第一个yield语句,所以没有返回任何内容,然后第二次调用next(),代码执行到第二个yield,包括第一个yield行,因此pretzel记录到控制台.

如果是这种情况,在下面提到的代码中如何0登录第一次呼叫next()?我在这里遗漏了一些东西:(

function* idMaker() {
  var index = 0;
  while (index < 3)
    yield index++;
}

var gen = idMaker();

console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); …
Run Code Online (Sandbox Code Playgroud)

javascript ecmascript-6

3
推荐指数
2
解决办法
1195
查看次数

标签 统计

ecmascript-6 ×1

javascript ×1