Set.prototype.union()尚未被任何浏览器原生支持,截至2024年仍处于TC39 Stage 3提案阶段,调用会抛出TypeError;需用new Set([...set1, ...set2])等手动方式替代。

Set.prototype.union() 尚未被任何浏览器原生支持,目前(截至 2024 年)它仍处于 TC39 提案 Stage 3 阶段,尚未进入 ECMAScript 正式标准。因此,无法直接使用 Set.prototype.union() 实现跨页面 ID 合并。
为什么不能直接用 union()?
当前主流浏览器(Chrome、Firefox、Safari、Edge)均未实现该方法。调用会抛出 TypeError: set.union is not a function。
- 提案中的
union()是实例方法,语法为set1.union(set2),返回新 Set - 它等价于扩展运算符 + 构造器写法:
new Set([...set1, ...set2]) - 但该能力需靠 polyfill 或手动实现,不能当作“已存在 API”直接调用
跨页面选中 ID 的去重合并实战方案
真实业务中,“跨页面”通常指:用户在多个列表页(如分页、多 Tab、搜索结果页)分别勾选实体,需在汇总页统一处理。关键在于状态持久化与合并逻辑。
-
持久化选中状态:用
localStorage存储一个全局 Set 的序列化形式(推荐 JSON 数组)
示例:localStorage.setItem('selectedIds', JSON.stringify(['101', '205', '317'])) -
页面间同步更新:每次勾选/取消时读取旧数组 → 转为 Set → 增删 → 再存回 localStorage
避免直接 push/splice 数组,防止重复 ID;用 Set 天然去重 -
合并逻辑(替代 union):
✓new Set([...setA, ...setB])—— 最简洁、兼容性好(ES2015+)
✓Array.from(new Set([...arrA, ...arrB]))—— 若需数组结果
✓ 手动遍历添加:const merged = new Set(setA); for (const id of setB) merged.add(id);
一个轻量可复用的跨页选中管理器
封装成工具类,自动处理 localStorage 读写与 Set 合并:
class CrossPageSelection {
constructor(key = 'selectedIds') {
this.key = key;
this.load();
}
load() {
const saved = localStorage.getItem(this.key);
this.set = new Set(saved ? JSON.parse(saved) : []);
}
save() {
localStorage.setItem(this.key, JSON.stringify([...this.set]));
}
add(id) {
this.set.add(String(id));
this.save();
}
delete(id) {
this.set.delete(String(id));
this.save();
}
// 模拟 union:合并另一个 Set 或数组
union(other) {
const otherSet = other instanceof Set
? other
: new Set(Array.isArray(other) ? other : [other]);
return new Set([...this.set, ...otherSet]);
}
values() {
return [...this.set];
}
}
// 使用示例
const selection = new CrossPageSelection();
selection.add('1001');
selection.add('1002');
// 在另一页面:
const otherSelection = new CrossPageSelection();
otherSelection.add('1002'); // 重复 ID 自动忽略
otherSelection.add('1003');
// 全量合并(等效 union)
const allIds = [...selection.union(otherSelection.values())]; // ['1001','1002','1003']
注意事项与边界情况
-
ID 类型一致性:确保所有页面都用字符串存储 ID(如后端返回 number,统一
String(id)),避免123和'123'被视为不同值 - Storage 容量限制:localStorage 约 5–10MB,但单个 key 通常限制在 2MB 内;ID 过多时考虑分页缓存或服务端暂存
-
多标签同步延迟:localStorage 不触发跨标签事件,可用
storage事件监听其他标签变更:window.addEventListener('storage', e => { if (e.key === 'selectedIds') manager.load(); }); - 隐私模式兼容性:部分浏览器隐私模式下 localStorage 可能被禁用,需降级为内存 Set 并提示用户










