ES2025 新特性详解
2025 年 6 月 25 日,Ecma 国际正式批准了 ECMAScript 2025(第 16 版)语言规范。ES2025 带来了迭代器辅助方法、Set 集合运算、Import Attributes、RegExp.escape、Promise.try、Float16Array 等多项实用特性,进一步提升了 JavaScript 的表达能力和开发效率。下面让我们深入了解这些新特性。
Import Attributes 与 JSON 模块
ES2025 引入 Import Attributes 语法,支持导入非 JavaScript 资源。其中 JSON 模块是首个内置支持的类型:
// 静态导入
import configData from './config-data.json' with { type: 'json' };
console.log(configData.apiUrl);
// 动态导入
const config = await import('./config.json', { with: { type: 'json' } });
with { type: 'json' } 指定导入属性,浏览器和 Node.js 会按 JSON 解析并返回数据对象,无需手动 fetch 或 readFile 后再 JSON.parse。
迭代器辅助方法
ES2025 为迭代器(Iterator)原型添加了与数组类似的方法,但采用惰性求值,不会创建中间数组,适合处理大量数据:
const arr = ['a', '', 'b', '', 'c', '', 'd', '', 'e'];
arr.values()
.filter((x) => x.length > 0)
.drop(1)
.take(3)
.map((x) => `=${x}=`)
.toArray();
// ['=b=', '=c=', '=d=']
返回迭代器的方法
iterator.map(mapFn)iterator.filter(filterFn)iterator.flatMap(mapFn)iterator.take(limit)— 取前 n 个元素iterator.drop(limit)— 跳过前 n 个元素
返回其他值的方法
iterator.reduce(reducer, initialValue?)iterator.find(fn)iterator.toArray()— 收集所有元素为数组
返回布尔值的方法
iterator.every(fn)iterator.some(fn)
无返回值的方法
iterator.forEach(fn)
与数组方法不同,迭代器方法是按元素逐个处理的:先对第一个元素应用所有操作,再对第二个元素,依次类推,从而避免中间数组和提前计算,适合流式或大数据集场景。
Set 新方法
ES2025 为 Set 新增了集合运算和关系判断方法。
集合运算
const setA = new Set(['a', 'b', 'c']);
const setB = new Set(['b', 'c', 'd']);
setA.union(setB); // Set(4) { 'a', 'b', 'c', 'd' }
setA.intersection(setB); // Set(2) { 'b', 'c' }
setA.difference(setB); // Set(1) { 'a' }
setA.symmetricDifference(setB); // Set(2) { 'a', 'd' }
关系判断
const small = new Set(['a', 'b']);
const large = new Set(['a', 'b', 'c']);
small.isSubsetOf(large); // true
large.isSupersetOf(small); // true
small.isDisjointFrom(new Set(['x', 'y'])); // true(无交集)
RegExp.escape()
RegExp.escape() 将字符串转义,使其安全地用于正则表达式,避免特殊字符被误解析:
const userInput = 'price (low)';
const regex = new RegExp(RegExp.escape(userInput), 'g');
'Get price (low) now'.replace(regex, '***'); // 'Get *** now'
在动态构建正则时,无需再手动转义 ()[]{}.*+?^$|\ 等字符,可有效防止正则注入和匹配错误。
正则表达式模式修饰符(内联标志)
可以在正则的局部使用 (?i:) 等修饰符,只影响括号内的部分:
/^x(?i:HELLO)x$/.test('xHELLOx'); // true
/^x(?i:HELLO)x$/.test('xhellox'); // true
/^x(?i:HELLO)x$/.test('XhelloX'); // false(只有 HELLO 部分不区分大小写)
重复命名捕获组
在 /v 标志下,允许在不同分支中使用相同的命名捕获组:
const RE = /(?<chars>a+)|(?<chars>b+)/v;
RE.exec('aaa').groups; // { chars: 'aaa' }
RE.exec('bb').groups; // { chars: 'bb' }
Promise.try()
Promise.try() 将同步代码包装为 Promise,同步抛出的错误会被转换为 rejected Promise:
function computeAsync() {
return Promise.try(() => {
const value = syncFuncMightThrow(); // 可能抛错
return asyncFunc(value);
});
}
// 等价于:
// const value = syncFuncMightThrow();
// return asyncFunc(value);
// 但 catch 可以统一捕获同步和异步错误
computeAsync().catch(handleError);
Float16Array(16 位浮点)
ES2025 新增 Float16Array 类型及相关 API,用于 16 位浮点数,在机器学习、图形等场景中可节省内存:
const buffer = new ArrayBuffer(4);
const view = new DataView(buffer);
view.setFloat16(0, 3.14); // 写入 16 位浮点
view.getFloat16(0); // 读取
const f16 = new Float16Array([1.5, 2.5, 3.5]);
ES2025 的这些新特性在模块导入、迭代处理、集合运算、正则表达、异步编程以及数值计算等方面都带来了显著改进。随着运行环境的逐步支持,开发者可以充分利用这些特性来提升开发效率和代码质量。
