next() 方法返回一个包含属性 done 和 value 的对象。该方法也可以通过接受一个参数用以向生成器传值。
语法
gen.next(value)
参数
-
value - 向生成器传递的值.
返回值
返回的对象包含两个属性:
done(布尔类型)- 如果迭代器超过迭代序列的末尾,则值为
true。 在这种情况下,value可选地指定迭代器的返回值。 - 如果迭代器能够生成序列中的下一个值,则值为
false。 这相当于没有完全指定done属性。
- 如果迭代器超过迭代序列的末尾,则值为
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。 请注意,第一次调用没有记录任何内容,因为生成器最初没有产生任何结果。
function* gen() {
while(true) {
var value = yield null;
console.log(value);
}
}
var g = gen();
g.next(1);
// "{ value: null, done: false }"
g.next(2);
// 2
// "{ value: null, done: false }"
规范
| 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 |