领先的免费Web技术教程,涵盖HTML到ASP.NET

网站首页 > 知识剖析 正文

ECMAScript 2025 来了,新功能一览!

nixiaole 2025-04-27 15:31:30 知识剖析 2 ℃

JavaScript 语言标准 ECMAScript 2025 候选版已于 3 月发布,正式版预计 6 月落地。

此次更新聚焦开发者痛点,从正则处理到异步编程均有实用性改进,以下选取核心特性展开分析,新功能一览:

Promise 和迭代器改进

Promise.try

Promise.try(fn) 用于将函数 fn 包装成 Promise,同步执行并处理异常,统一同步和异步行为。

以前,处理可能同步或异步的函数需要 Promise.resolve().then(fn),但这异步执行,影响性能;或用 new Promise(resolve => resolve(fn())),代码冗长。

function mightThrow() {
  if (Math.random() > 0.5) throw new Error("Oops");
  return "Success";
}
Promise.resolve().then(mightThrow)
  .then(result => console.log(result))
  .catch(error => console.error(error));

在 ES2025 中可以这样:

Promise.try(mightThrow)
  .then(result => console.log(result))
  .catch(error => console.error(error));

同步迭代器辅助函数

Iterator.prototype 添加方法如 mapfiltertakedrop 等,增强迭代器操作,类似数组方法。

以前,操作迭代器需要自定义生成器函数。

function* mapIterator(iter, mapper) {
  for (const value of iter) {
    yield mapper(value);
  }
}
const iter = [1, 2, 3][Symbol.iterator]();
const mappedIter = mapIterator(iter, x => x * 2);
for (const value of mappedIter) {
  console.log(value); // 2, 4, 6
}

在 ES2025 中可以这样:

const iter = [1, 2, 3][Symbol.iterator]();
const mappedIter = iter.map(x => x * 2);
for (const value of mappedIter) {
  console.log(value); // 2, 4, 6
}

正则表达式增强

RegExp.escape()

动态拼接正则表达式时,用户输入中的特殊字符(如 *$)常引发语法错误或安全漏洞。以往需手动编写转义函数:

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\');
}
const text = "Hello (World)";
const regex = new RegExp(escapeRegExp(text), 'g');

ES2025 新增原生方法 RegExp.escape(),一行代码即可安全转义,避免正则注入风险:

const text = "Hello (World)";
const regex = new RegExp(RegExp.escape(text), 'g');
console.log(regex.test("Hello (World)")); // true

浏览器支持情况:

正则表达式模式修饰符

ES2025 将允许在正则表达式中动态启用或禁用标志(如 ims),使用语法如 (?i:pattern) 或 (?-i:pattern)。

以前,标志只能应用于整个正则表达式,无法局部控制。例如,匹配部分不区分大小写需要拆分正则或使用复杂技巧,这大大限制了复杂模式的表达能力。

在 ES2025 中可以这样:

const regex = /^(?i:abc)def(?-i:ghi)$/;
console.log(regex.test("AbcDefGHI")); // true

重复命名捕获组

ES2025 将允许在正则表达式的不同分支中使用相同的命名捕获组名称,只要这些组不会同时匹配。例如,(?<year>\d{4}) 可以出现在多个分支中。

以前,命名捕获组必须唯一,导致匹配不同格式时需要使用不同组名。在访问结果时需额外逻辑判断,复杂且冗长,限制了正则表达式的灵活性。

const regex = /^(?<year>\d{4})-(?<month>\d{2})|(?<year2>\d{4})\/(?<month2>\d{2})$/;

在 ES2025 中可以这样:

const regex = /^(?<year>\d{4})-(?<month>\d{2})|(?<year>\d{4})\/(?<month>\d{2})$/;
const match1 = regex.exec("2025-04");
console.log(match1.groups.year, match1.groups.month); // 2025 04

集合和模块更新

新的 Set 方法

为内置 Set 类添加新方法,如 union(并集)、intersection(交集)、difference(差集)等,提升集合操作的便利性。

const setA = new Set([1, 2, 3]);
const setB = new Set([2, 3, 4]);
console.log(setA.union(setB)); // Set {1, 2, 3, 4}
console.log(setA.intersection(setB)); // Set {2, 3}

浏览器支持:

JSON 模块

ES2205 将允许直接导入 JSON 文件,语法:import ... with { type: 'json' };

以前,导入 JSON 需要借助 fetchfs来实现:

fetch('./config.json')
  .then(response => response.json())
  .then(data => console.log(data));

在 ES2025 中可以这样:

import config from './config.json' with { type: 'json' };
console.log(config);

导入属性

import 中添加属性,使用 with 指定模块类型,如 with { type: 'json' };

以前,模块类型由扩展名推断,可能导致安全问题。

const config = require('./config.json');

在 ES2025 中可以这样:

import config from './config.json' with { type: 'json' };

TypedArray 增强

Float16Array

添加 Float16Array TypedArray 和相关方法,支持 16 位浮点数。

以前,JavaScript 只支持 32 位和 64 位浮点数,16 位浮点数需库支持,效率较低。

const float16 = require('@petamoriken/float16');
const arr = new float16.Float16Array([1.0, 2.3, 3.4]);

在 ES2025 中可以这样:

const arr = new Float16Array([1.0, 2.3, 3.4]);
console.log(arr[0]); // 1

不过,Float16Array 主要用于图形和机器学习,可能在普通开发中影响有限。

最近发表
标签列表