写过前端的都以为数组配对只能靠 lodash,今天 ES2027 把这件事彻底原生化了

写过前端的都踩过这个坑——要把两个数组合成一个 Map,以前只能 npm install lodash,再写个 .zip 或者 .fromPairs,代码绕来绕去。今天 ES2027 给了你一个原生 API,一行搞定。

Iterator.zip() 是 TC39 Stage 4 标准,Chrome 153、Edge 153、Firefox 148 全部稳定支持,Node.js、Bun、Deno 早就上了。换句话说——你现在写的任何项目都能用。

核心用法

Iterator.zip 接受一个可迭代对象的数组,把它们按位置配对,产出元组:

const keys = ["Mon", "Tue", "Wed"];
const temps = [22, 21, 23];

for (const [day, temp] of Iterator.zip([keys, temps])) {
  console.log(`${day}: ${temp}°C`);
}
// Mon: 22°C
// Tue: 21°C
// Wed: 23°C

最典型的用法——两个数组直接转 Map:

const dayTemperatureMap = new Map(Iterator.zip([keys, temps]));
// Map(3) { Mon => 22, Tue => 21, Wed => 23 }

这替代了以前一整块 lodash 代码:

// 以前
import { zip, fromPairs } from "lodash";
const map = new Map(fromPairs(zip(keys, temps)));

// 现在
const map = new Map(Iterator.zip([keys, temps]));

三种模式,处理长度不一致

Iterator.zip 的第二个参数是 options,支持 mode:

  • shortest(默认):遇到最短的数组就停,适合处理不等长数据
  • longest:等所有数组跑完,短的那几个用 padding 填或者 undefined
  • strict:长度不一致直接抛 TypeError,用于你确信数据一定等长的情况
// 不等长,走 longest,自动补 undefined
const letters = ["a", "b", "c", "d"];
const numbers = [1, 2, 3];

for (const [l, n] of Iterator.zip([letters, numbers], { mode: "longest" })) {
  console.log(`${l}: ${n}`);
}
// a: 1
// b: 2
// c: 3
// d: undefined

// 指定 padding
const padding = ["[无]", "[缺]"];
for (const [l, n] of Iterator.zip([letters, numbers], { mode: "longest", padding })) {
  console.log(`${l}: ${n}`);
}
// a: 1
// b: 2
// c: 3
// d: [缺]

还有一个 zipKeyed,产出对象

如果你的场景里用对象比用 Map 更顺手,zipKeyed 更直观:

const names = ["Alice", "Bob"];
const scores = [95, 87];

for (const record of Iterator.zipKeyed({ name: names, score: scores })) {
  console.log(record);
}
// { name: Alice, score: 95 }
// { name: Bob, score: 87 }

惰性求值是精髓

Iterator.zip 返回的是一个迭代器,不是数组。这意味着一件事:它不会先把所有数据都加载进内存。

// 无限序列也可以配对——只要最短的那个先跑完,整个迭代就停了
function* naturals() { let n = 0; while (true) yield n++; }
function* odds() { let n = 1; while (true) yield (n += 2); }

const pairs = Iterator.zip([naturals(), odds()]);
console.log(pairs.next().value); // [0, 1]
console.log(pairs.next().value); // [1, 3]
console.log(pairs.next().value); // [2, 5]
// 惰性,按需取,不爆内存

而且当迭代终止时,所有输入的迭代器都会被正确关闭,不会造成内存泄漏。

浏览器兼容性

  • Chrome 153+ ✅
  • Edge 153+ ✅
  • Firefox 148+ ✅
  • Safari 还没上(26.6 仍不支持),但可以用 polyfill
  • Node.js 22+ ✅

下一步

如果你现在还在用 lodash 的 zip,第一步很简单——搜一下项目里 import from “lodash” 的 zip 相关调用,替换成 Iterator.zip,然后删掉这个 lodash 依赖。平均每个项目能省 30KB 左右的 bundle。

如果你的项目要兼容 Safari,用 core-js 的 polyfill 或者直接写一个几百字节的轻量实现也行——这个 API 的核心逻辑非常简单。

TC39 正在推进的下一个类似提案是 iterator chunking(chunks/windows),未来连 lodash 的 chunk 和 window 都可以替代了。

评论区

0 条评论

登录后可评论。

铁锈·Rust工具链 2052 阅读