Generator.next()如何处理其参数? [英] How does Generator.next() processes its parameter?

查看:135
本文介绍了Generator.next()如何处理其参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档说, 您还可以为下一个方法提供参数,以将值发送到生成器."它发送到哪里?

The documentation says that "You can also provide a parameter to the next method to send a value to the generator." Where does it sends it to?

例如,使用以下3个生成器:

For example, take these 3 generators:

function* one() {
  while(true) {
    var value = yield null;
  }
}
var g1 = one();  g1.next();
g1.next(1000); //yields null

function* two() {
  var i = 0;
  while (true) {
    i += yield i;
  }
}
var g2 = two(); g2.next(); 
g2.next(1000) // yields 1000

function* three(){
  var index = 0;
  while (true)
    yield index++;
}

 g3 = three();
 g3.next();
 g3.next(1000); // yields 1

在生成器3和1中,传递的参数对next无效.这是为什么?生成器2如何计算其返回值?为什么它会受到给定参数的影响?

In generators 3 and 1, the argument passed has no effect on next. Why is that? How does generator 2 calculates its return value? Why it is affected by the given argument?

推荐答案

了解这一点的关键是知道下一个函数如何检索传递给next()的参数,该参数作为yield运算符的返回值:

The key to understanding this is knowing how the next function retrieves the argument passed to next(), which is as the return value of the yield operator:

[rv] = yield [expression];

与[expression]的值无关,yield将为传递给next()的值分配给rv.

Independently of the value of [expression], yield will assign to rv the value passed to next().

但是,这是一个棘手的部分:yield仅在恢复上一次迭代的执行时才将传递给next()的值赋值.因此,在第一次迭代中,yield不会为rv分配任何内容.

But, here comes the tricky part: yield will only assign the value passed to next() when resuming execution from a previous iteration. As a consequence, on the first iteration, yield does not assign anything to rv.

例如,如果我有此生成器:

For example, if I have this generator:

function* gen() {
  // On the first iteration, yield does not return anything.
  //because it returns something ONLY when execution is resumed
  returnedFromYield = yield 'foo'; 
  yield returnedFromYield; 
}

returnedFromYield在第一次迭代中未定义.在第二次迭代中恢复执行时,yield将传递的值分配给returnedFromYield变量,然后将其返回:

returnedFromYield is undefined on the first iteration. When execution is resumed on the second iteration, yield assigns the passed value to the returnedFromYield variable, which is then returned:

g.next(1); // 'foo'
g.next(2); // 2

让我们回顾另一个示例:

Let's review another example:

function* gen() {
  yield yield yield 5;
}

在第一个迭代(g.next())上,收益将返回5,在第二个迭代中,(g.next(10))收益将传递10到第二个收益.也就是说,第二次迭代中的yield yield yield 5;等效于yield yield 10;,第三次迭代中的yield yield yield 5;等效于yield valuePassedToNext.

On the first iteration, (g.next()), yield will return 5, on the second iteration, (g.next(10)) yield is going to pass 10 to the second yield. That is, yield yield yield 5; on the second iteration is equivalent to yield yield 10;, and, on the third iteration, it's equivalent to yield valuePassedToNext.

这篇关于Generator.next()如何处理其参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆