Generator.prototype.next()
Generator
实例的 next()
方法返回一个具有两个属性 done
和 value
的对象。你还可以向 next
方法提供参数以将值发送到生成器。
¥The next()
method of Generator
instances returns an
object with two properties done
and value
. You can also
provide a parameter to the next
method to send a value to the
generator.
语法
参数
¥Parameters
value
Optional-
要发送到生成器的值。
该值将被指定为
yield
表达式的结果。例如,在variable = yield expression
中,传递给.next()
函数的值将被分配给variable
。
返回值
示例
使用 next()
¥Using next()
以下示例显示了一个简单的生成器和 next
方法返回的对象:
¥The following example shows a simple generator and the object that the
next
method returns:
function* gen() {
yield 1;
yield 2;
yield 3;
}
const g = gen(); // Generator { }
g.next(); // { value: 1, done: false }
g.next(); // { value: 2, done: false }
g.next(); // { value: 3, done: false }
g.next(); // { value: undefined, done: true }
将 next() 与列表一起使用
¥Using next() with a list
在此示例中,getPage
获取一个列表,"paginates" 将其分成大小为 pageSize
的块。每次调用 next
都会产生一个这样的块。
¥In this example, getPage
takes a list and "paginates" it into chunks of size pageSize
. Each call to next
will yield one such chunk.
function* getPage(list, pageSize = 1) {
for (let index = 0; index < list.length; index += pageSize) {
yield list.slice(index, index + pageSize);
}
}
const list = [1, 2, 3, 4, 5, 6, 7, 8];
const page = getPage(list, 3); // Generator { }
page.next(); // { value: [1, 2, 3], done: false }
page.next(); // { value: [4, 5, 6], done: false }
page.next(); // { value: [7, 8], done: false }
page.next(); // { value: undefined, done: true }
将值发送到生成器
¥Sending values to the generator
在此示例中,使用值调用 next
。
¥In this example, next
is called with a value.
注意:第一次调用不会记录任何内容,因为生成器最初没有产生任何内容。
¥Note: The first call does not log anything, because the generator was not yielding anything initially.
function* gen() {
while (true) {
const value = yield;
console.log(value);
}
}
const g = gen();
g.next(1); // Returns { value: undefined, done: false }
// No log at this step: the first value sent through `next` is lost
g.next(2); // Returns { value: undefined, done: false }
// Logs 2
规范
Specification |
---|
ECMAScript Language Specification # sec-generator.prototype.next |
浏览器兼容性
BCD tables only load in the browser