Generator - JavaScript 编辑
The Generator
object is returned by a generator function and it conforms to both the iterable protocol and the iterator protocol.
Constructor
This object cannot be instantiated directly. Instead, a Generator
instance can be returned from a generator function:
function* generator() { yield 1; yield 2; yield 3; } const gen = generator(); // "Generator { }" console.log(gen.next().value); // 1 console.log(generator().next().value); // 1 console.log(generator().next().value); // 1
Instance methods
Generator.prototype.next()
- Returns a value yielded by the
yield
expression. Generator.prototype.return()
- Returns the given value and finishes the generator.
Generator.prototype.throw()
- Throws an error to a generator (also finishes the generator, unless caught from within that generator).
Examples
An infinite iterator
function* infinite() {
let index = 0;
while (true) {
yield index++;
}
}
const generator = infinite(); // "Generator { }"
console.log(generator.next().value); // 0
console.log(generator.next().value); // 1
console.log(generator.next().value); // 2
// ...
Specifications
Specification |
---|
ECMAScript (ECMA-262) The definition of 'Generator objects' in that specification. |
Browser compatibility
BCD tables only load in the browser
See also
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论