ES2025
ES2025 (ECMAScript 16) 带来了多项增强 JavaScript 开发体验和性能的新特性。
1. Set 集合的新方法 (New Set Features)
JavaScript 原生的 Set 对象新增了许多数学集合运算的内置方法,不再需要依赖第三方库或手动实现循环:
Set.prototype.union(other):返回两个集合的并集。Set.prototype.intersection(other):返回两个集合的交集。Set.prototype.difference(other):返回两个集合的差集(在当前集合但不在 other 集合中)。Set.prototype.symmetricDifference(other):返回对称差集(存在于任意一个集合但不同时存在于两个集合中)。Set.prototype.isSubsetOf(other):判断当前集合是否是 other 集合的子集。Set.prototype.isSupersetOf(other):判断当前集合是否是 other 集合的超集。Set.prototype.isDisjointFrom(other):判断两个集合是否完全没有交集。
const A = new Set(['a', 'b', 'c']);
const B = new Set(['b', 'c', 'd']);
console.log(A.union(B)); // Set { 'a', 'b', 'c', 'd' }
console.log(A.intersection(B)); // Set { 'b', 'c' }
console.log(A.difference(B)); // Set { 'a' }
2. Iterator 辅助方法 (Iterator Helpers)
为迭代器 (Iterator) 提供了类似于数组的函数式接口。其最大优势是 惰性求值 (Lazy Evaluation),在处理极大数据集时,不需要像数组方法那样在每一步创建中间数组,从而大幅提升性能并减少内存开销。
新增方法包括:.map(), .filter(), .reduce(), .find(), .some(), .every(), .flatMap(), .forEach(),以及独有的方法:
.drop(limit):跳过前limit个元素。.take(limit):只获取前limit个元素。.toArray():将剩余的迭代结果收集为数组。
const arr = ['a', '', 'b', '', 'c', '', 'd', '', 'e'];
const result = arr.values() // 创建原生迭代器
.filter(x => x.length > 0) // 惰性过滤
.drop(1) // 惰性跳过第1个非空项
.take(3) // 惰性取3项
.map(x => `=${x}=`)
.toArray();
console.log(result); // ['=c=', '=d=', '=e=']
3. Import Attributes (导入属性)
正式引入了导入属性,用于导入非 JavaScript 类型的模块(如 JSON)。
// 静态导入 JSON
import config from './config.json' with { type: 'json' };
// 动态导入 JSON
const data = await import('./data.json', {
with: { type: 'json' }
});
4. 正则表达式增强
/vflag:作为/u(unicode) 标志的升级版,支持更高级的 Unicode 字符串操作,例如允许在正则表达式的字符类中执行集合运算。RegExp.escape():用于转义字符串中包含的所有特殊正则表达式字符。
5. 其他新特性
Float16Array/Math.f16round():支持了 16 位的浮点数 TypedArray,在 WebGL、GPU 计算或机器学习等对内存敏感的场景中非常有用。Promise.try():提供了一种便捷的方式,无论是同步还是异步函数,都能统一放入 Promise 链中执行,避免了自己使用new Promise(resolve => resolve(func()))的繁琐包装。