Please note, this is a STATIC archive of website developer.mozilla.org from November 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Generator.prototype.next()

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

语法

gen.next(value)

参数

value
向生成器传递的值.

返回值

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

  • done (布尔类型)
    • 当迭代器遍历到迭代序列末端时返回值 true . In this case value optionally specifies the return value of the iterator.
    • 当迭代器仍可继续在迭代序列中向前遍历时返回值 false. This is equivalent of not specifying the done property altogether.
  • value - 迭代器返回的任意的Javascript值. 当 done 的值为 true 时可以忽略该值.

示例

使用 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 方法时没有出任何输出, 这是因为初始状态时生成器通过yield 返回了null.

function* gen() {
  while(true) {
    var value = yield null;
    console.log(value);
  }
}

var g = gen();
g.next(1); 
// "{ value: null, done: false }"
g.next(2); 
// "{ value: null, done: false }"
// 2

规范

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
Generator.prototype.next
Standard Initial definition.
ECMAScript 2017 Draft (ECMA-262)
Generator.prototype.next
Draft  

浏览器兼容性

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support ? 26 (26) ? ? ?
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? ? 26.0 (26) ? ? ?

相关链接

文档标签和贡献者

 此页面的贡献者: Ende93, lukywong, jcouyang
 最后编辑者: Ende93,