跳到主要内容

Generator 函数是什么,有什么作用?

面试速答(30 秒版 TL;DR)

  • Generator 是用 function* 定义的函数,返回一个生成器对象(本质上是一个 iterator)。
  • yield 可以“暂停函数执行并产出一个值”,下次 next() 再从暂停点继续。
  • 作用:实现惰性序列、更容易地实现 iterator、以及某些协程式控制流(现代业务里控制流多被 async/await 取代,但生成器做迭代仍很有用)。

最小例子:生成器就是一个 iterator

function* gen() {
yield 1;
yield 2;
return 3;
}

const it = gen();
console.log(it.next()); // { value: 1, done: false }
console.log(it.next()); // { value: 2, done: false }
console.log(it.next()); // { value: 3, done: true }

面试细节:return 的值会出现在最后一次 done: true 的结果里,但 for...of 会忽略这个“最终 return 值”。


典型用途 1:快速实现可迭代对象

const iterable = {
*[Symbol.iterator]() {
yield 'a';
yield 'b';
},
};

console.log([...iterable]); // ["a", "b"]

对比手写 iterator:生成器省掉了维护 curdone 这些样板代码。


典型用途 2:惰性生成(lazy)

function* naturals() {
let n = 0;
while (true) yield n++;
}

const it = naturals();
console.log(it.next().value); // 0
console.log(it.next().value); // 1

常见追问

  • yield*:把迭代委托给另一个 iterable/iterator。
  • next(value):可以把值“送回”到上一个 yield 表达式处(用来做双向通信)。
  • throw(err) / return(value):用于中断生成器或注入异常。

易错点/坑

  • for...of 不会遍历生成器最终的 return 值。
  • 生成器不是 async:要异步迭代要用 async function* + for await...of(面试时按场景补充即可)。

速记要点(可背诵)

  • Generator:function* + yield,返回 iterator,可暂停/恢复执行。
  • 常用来实现 iterable、惰性序列。