迭代器与生成器是JavaScript处理数据序列的核心工具,通过Iterator协议的next()方法返回{value, done}对象,实现对数据的惰性访问;生成器函数(function*)利用yield暂停执行,按需产出值,提升性能与可读性;可应用于异步流程控制(如生成器+Promise实现同步写法)、无限序列(如斐波那契数列)等场景,避免内存溢出;结合for...of遍历并配合简易运行器处理异步操作,是co库与早期Koa的基础,有助于写出高效、表达力强的代码。

JavaScript 中的迭代器与生成器是处理数据序列的强大工具,尤其在面对大量或动态生成的数据时,能有效提升代码可读性与性能。它们不只是语言特性的点缀,而是函数式编程和异步流程控制的重要基础。
迭代器是一种设计模式,允许你访问聚合对象中的元素而不暴露其内部表示。在 JavaScript 中,一个迭代器是一个符合 Iterator 协议 的对象,即拥有一个 next() 方法,返回形如 { value, done } 的结果对象。
实现一个简单的计数器迭代器:
const counter = {
current: 0,
max: 5,
next() {
if (this.current < this.max) {
return { value: ++this.current, done: false };
} else {
return { done: true };
}
},
[Symbol.iterator]() {
return this;
}
};
<p>for (const num of counter) {
console.log(num); // 输出 1 到 5
}</p>注意:为了让对象可被 for...of 遍历,必须实现 [Symbol.iterator] 方法,这使对象成为可迭代对象(Iterable)。
立即学习“Java免费学习笔记(深入)”;
手动实现迭代器较为繁琐,而生成器函数提供了一种更优雅的方式。使用 function* 定义的函数会返回一个生成器对象,该对象既是迭代器也是可迭代对象。
用生成器重写上面的计数器:
function* counterGenerator(max) {
let current = 0;
while (current < max) {
yield ++current;
}
}
<p>for (const num of counterGenerator(5)) {
console.log(num); // 输出 1 到 5
}</p>yield 关键字暂停函数执行并返回值,下次调用 next() 时从暂停处继续。这使得复杂的数据流控制变得直观。
虽然现在普遍使用 async/await,但生成器曾是协程式异步处理的核心。通过配合一个运行器,可以实现类似 async 函数的效果。
示例:用生成器实现异步流程控制
function fetchData(url) {
return new Promise(resolve => {
setTimeout(() => resolve(`Data from ${url}`), 1000);
});
}
<p>function* asyncFlow() {
const data1 = yield fetchData('api/user');
const data2 = yield fetchData('api/posts');
return <code>${data1} | ${data2}</code>;
}</p><p>// 简易运行器
function run(generatorFunc) {
const iterator = generatorFunc();
function handle(result) {
if (result.done) return Promise.resolve(result.value);
return Promise.resolve(result.value).then(
res => handle(iterator.next(res)),
err => iterator.throw(err)
);
}
return handle(iterator.next());
}</p><p>run(asyncFlow).then(console.log); // 一秒后输出合并数据</p>这种模式是 co 库和早期 Koa 框架的基础,展示了生成器对异步逻辑同步书写的强大支持。
生成器不会一次性生成所有值,而是按需产生,适合处理无限序列或大数据集。
例如,生成斐波那契数列:
function* fibonacci() {
let a = 0, b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
<p>const fib = fibonacci();
console.log(fib.next().value); // 0
console.log(fib.next().value); // 1
console.log(fib.next().value); // 1
console.log(fib.next().value); // 2</p>你可以随时取值,而无需担心内存溢出。结合 for...of 和条件中断,可安全遍历有限部分。
基本上就这些。掌握迭代器与生成器,不仅有助于理解现代 JS 的底层机制,还能写出更高效、更具表达力的代码。不复杂但容易忽略。
以上就是JavaScript_迭代器与生成器深入应用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号