你以为 concat 只能拼接数组?今天 ES2026 把这件事用 Iterator 彻底原生化了
拼接两个数组你会用 concat,拼接三个你会 ...spread,拼接 Generator 加数组你怎么办?
这个问题困扰了 JS 开发者很多年——直到 ES2026 的 Iterator.concat() 来了。
痛点:拼接迭代器没有标准做法
以前拼接多个可迭代对象(数组、Set、Generator、Map.values()),没有统一方案:
// 数组可以,但 Generator 不行
const merged = [...arr1, ...arr2];
// 惰性拼接 Generator?只能手写生成器
function* combine(...iters) {
for (const it of iters) yield* it;
}
[...arr1, ...arr2] 的问题是:会立即把所有数据物化成数组,内存里存两份数据。Generator 那种用多少取多少的惰性优势直接没了。
Iterator.concat():惰性拼接任意可迭代对象
const it = Iterator.concat(['a', 'b'], new Set([1, 2]), naturals());
核心特点:
- 惰性求值:第一个可迭代对象全部消费完才动第二个,永远不会在内存里同时存两份
- 任意类型混拼:数组、Set、Map、Generator,什么类型都能接
- 兼容所有 Iterator helpers:
.filter()、.map()、.take()、.toArray()全部能用 - ES2026 新标准:Chrome 146+、Firefox 147+、Safari 26.4+ 全部支持,覆盖率约 78%
真实场景:合并多个 API 分页
async function* fetchAllPages(endpoint) {
let url = endpoint;
while (url) {
const res = await fetch(url);
const { data, nextPage } = await res.json();
yield* data;
url = nextPage;
}
}
async function* fetchMultiEndpoints(endpoints) {
yield* Iterator.concat(...endpoints.map(fetchAllPages));
}
以前这种场景要手动维护分页状态,现在 Iterator.concat() 帮你把多个异步 Generator 拼成一条惰性流——内存只存当前页,数据用完即弃。
对比:为什么比 [...a, ...b] 更好
[...a, ...b] |
Iterator.concat(a, b) |
|
|---|---|---|
| 惰性 | ❌ 立即展开成数组 | ✅ 第一个消费完才动第二个 |
| 内存峰值 | O(n+m) 同时存两份 | O(1) 逐个消费 |
| 无限流 | ❌ 内存爆炸 | ✅ 可以接无限 Generator |
| 任意可迭代对象 | ✅ 支持 | ✅ 支持(含非数组类型) |
| Iterator helpers | ❌ 没有 | ✅ filter/map/take 全套 |
三步上手
第一步:确认环境
if (!Iterator.concat) {
console.error('浏览器不支持 Iterator.concat,需要 polyfill');
}
第二步:替换手写生成器
// 旧写法
function* combine(...iters) {
for (const it of iters) yield* it;
}
// 新写法
const combined = Iterator.concat(...iters);
第三步:结合 Iterator helpers 做链式处理
const result = Iterator.concat(jsonFiles)
.filter(line => line.trim())
.map(JSON.parse)
.take(100)
.toArray();
结论
Iterator.concat() 把 JS 的惰性序列能力正式纳入标准库。以前处理流式数据(文件行、分页 API、日志流)总要手写 Generator 拼接逻辑,或者干脆 [...a, ...b] 暴力展开换内存换性能。现在一行搞定——用多少取多少,永远不浪费。
适合三种人:
- 处理大文件或分页 API:内存友好,不卡浏览器
- 写数据管道:结合 Iterator helpers 做链式过滤/映射
- 写框架或库:统一惰性拼接接口,不用自己维护状态
下一步去 MDN 文档查完整 API 示例,试着把项目里那些手写的 Generator 拼接函数替换掉。
评论区
0 条评论
登录后可评论。