next() 方法返回一个包含属性 donevalue 的对象。该方法也可以通过接受一个参数用以向生成器传值。

语法

gen.next(value)

参数

value
向生成器传递的值.

返回值

返回的对象包含两个属性:

示例

使用 next()方法

下面的例子展示了一个简单的生成器, 以及调用 next 后方法的返回值:

function* gen() { 
  yield 1;
  yield 2;
  yield 3;
}

var g = gen(); // "Generator { }"
g.next();      // "Object { value: 1, done: false }"
g.next();      // "Object { value: 2, done: false }"
g.next();      // "Object { value: 3, done: false }"
g.next();      // "Object { value: undefined, done: true }"

向生成器传值

在该示例中,调用 next 方法并传入了参数,请注意,首次调用 next 方法时参数0被丢弃.

/** gen函数运行解析:
 * i=0 时传入参数(0),并将参数0赋给上一句yield的返回赋值,由于没有上一句yield语句,这步被忽略
 * 执行var val =100,然后执行yield val,此时g.next(i)返回{ value: 100, done: false }
 * 然后console.log(i,g.next(i).value),打印出0 100
 *
 * i=1 时传入参数(1),并将参数1赋给上一句yield的返回赋值,即(val = 1)
 * 然后执行console.log(val),打印出1。
 * 接着进入第二次while循环,调用yield val,此时g.next(i)返回{ value: 1, done: false }
 * 然后console.log(i,g.next(i).value),打印出1 1
 *
 * i=2 ....(省略)
 */
function* gen() {
   var val =100;
   while(true) {
      val = yield val;
      console.log(val);
   }
}

var g = gen();
for(let i =0;i<5;i++){
   console.log(i,g.next(i).value);
}

/* 返回:
 0 100
 1
 1 1
 2
 2 2
 3
 3 3
 4
 4 4
*/

向生成器传值的示例数据流向解析

规范

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
Generator.prototype.next
Standard 初始定义
ECMAScript Latest Draft (ECMA-262)
Generator.prototype.next
Draft 草案

浏览器兼容性

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!
Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) 13 26 (26) 未实现 (Yes) 10
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support 5.1 (Yes) 26.0 (26) ? ? 10

相关链接