Skip to content

Generator

一句话解释

generator 是 函数 declared 使用 函数* 那个 能 暂停 execution 使用 yield and 恢复 later, producing 序列 的 值.

用大白话说

generator 函数 (declared 使用 function*) 能暂停它的 execution 使用 yield keyword and 恢复 later. 每个时间你 call next() on generator 对象, 它运行直到下一个 yield and returns the yielded value.

Generators are a convenient way to create custom iterators. They are lazy — values are produced on demand, not all at once. This makes them useful for large sequences, infinite sequences, or complex iteration patterns.

You can also send values back into a generator by passing an argument to 下一个(值) — the yield expression evaluates to that value. This enables two-way communication between the generator and its consumer.

示例

javascript
function* range(start, end) {
  for (let i = start; i < end; i++) {
    yield i;
  }
}
for (const n of range(1, 4)) {
  console.log(n); // 1, 2, 3
}

generator yields 值 1, 2, 3 lazily. for...的 consumes generator.

相关术语

相关资源

相关课程

  • 函数

    学习 关于 generators.

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表