Collection methods S1
中文标题:集合方法
提案概览
- 阶段: Stage 1
- 状态: 进行中
- ECMAScript 版本: —
- 同步时间: 2026年8月26日
- English original · 官方仓库
提案速览
该提案为 Set、Map、WeakSet 和 WeakMap 原型添加了常见的类数组方法(如 filter、map、find、reduce、join、some、every)以及新的批量操作(如 addAll、deleteAll、merge、keyBy、update)。其目标是在不引入新语法的情况下减少样板代码,并使集合 API 与熟悉的 Array 方法保持一致。
Note
以下 README 来自上游仓库,其中的阶段或状态标注可能滞后;当前信息以提案概览为准。
新的集合(Set 和 Map)方法
参见正式规范草案。
(半)相关的先前讨论
- Map#map 和 Map#filter
- Map.prototype.map 和 Map.prototype.filter(规范)+ Set
- Map:filter/map 及更多
- 关于此提案的原始主题
- 关于此提案的较新主题
动机
- 它与已经熟悉且广泛使用的
ArrayAPI 保持一致(减少认知负担)- 更容易重构
- 某些函数变得通用
- 减少处理常见集合用例时的样板代码
- 不引入新语法
- 允许来自其他语言的开发者使用熟悉的 API
采用情况
待定
其他语言类似数据结构的快速参考
Set
Map(也称为 Dictionary)
待定
提案
本提案不改变语言的语法。
新方法被添加到 Set.prototype。
- 类数组方法。这些方法复刻了
Array.prototype方法的功能:Set.prototype.filter(predicate, thisArg)Set.prototype.map(fn, thisArg)Set.prototype.find(fn, thisArg)Set.prototype.reduce(fn, initialValue)Set.prototype.join(separator)Set.prototype.some(predicate, thisArg)Set.prototype.every(predicate, thisArg)
- 新方法:
Set.prototype.addAll(...elements)- 类似于Array.prototype.push。将所有参数添加到现有的Set中。- 替代名称:
.addEach
- 替代名称:
Set.prototype.deleteAll(...elements)-addAll的反向操作。从现有的Set中移除elements中的每个元素。- 替代名称:
.deleteEach
- 替代名称:
新方法被添加到 Map.prototype。
-
类数组方法。这些方法复刻了
Array.prototype方法的功能:Map.prototype.filter(predicate, thisArg)Map.prototype.mapValues(fn, thisArg)Map.prototype.mapKeys(fn, thisArg)Map.prototype.reduce(fn, initialValue)Map.prototype.find(fn, thisArg)Map.prototype.findKey(fn, thisArg)Map.prototype.keyOf(searchElement)Map.prototype.some(predicate, thisArg)Map.prototype.every(predicate, thisArg)Map.prototype.includes(searchElement)Map.prototype.update(key, callbackfn, thunk)
-
新方法:
Map.prototype.deleteAll(...elements)- 类似于Set.prototype.deleteAll。Map.prototype.merge(...iterables)- 执行原地更新,合并任意数量的可迭代对象。Map.prototype.update(key, cb [, thunk])- 对单个值执行原地更新。
新方法被添加到 %Map%:
Map.keyBy(iterable, keyDerivative)-
新方法被添加到 WeakSet.prototype。
- 新方法:
WeakSet.prototype.addAll(...elements)- 类似于Set.prototype.addAll。WeakSet.prototype.deleteAll(...elements)- 类似于Set.prototype.deleteAll。
新方法被添加到 WeakMap.prototype:
WeakMap.prototype.deleteAll(...elements)- 类似于Map.prototype.deleteAll。
Polyfill
Polyfill 可在 core-js 库中找到。 您可以在 ECMAScript 提案部分 / Stage 1 提案 / 新的 Set 和 Map 方法提案 下找到它。
对于所有新的集合方法,请在您的入口点顶部包含以下内容。
对于特定方法,请直接包含所需的 polyfill。
本提案不包含但值得考虑的
Set.prototype.flatMap、Set.prototype.flat- 如果Array.prototype.flatMap被添加到语言中,则应添加
为什么不是 %IteratorPrototype% 方法
参见 stage 3 Iterator Helpers 提案。
理由
详见 rationales.md。