ECMAScript 2025 來了,新功能一覽!
JavaScript 語言標準 ECMAScript 2025 候選版已于 3 月發(fā)布,正式版預(yù)計 6 月落地。
此次更新聚焦開發(fā)者痛點,從正則處理到異步編程均有實用性改進,以下選取核心特性展開分析,新功能一覽:
Promise 和迭代器改進
Promise.try
Promise.try(fn) 用于將函數(shù) fn 包裝成 Promise,同步執(zhí)行并處理異常,統(tǒng)一同步和異步行為。
以前,處理可能同步或異步的函數(shù)需要 Promise.resolve().then(fn),但這異步執(zhí)行,影響性能;或用 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));
同步迭代器輔助函數(shù)
為 Iterator.prototype 添加方法如 map、filter、take、drop 等,增強迭代器操作,類似數(shù)組方法。
以前,操作迭代器需要自定義生成器函數(shù)。
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()
動態(tài)拼接正則表達式時,用戶輸入中的特殊字符(如 *、$)常引發(fā)語法錯誤或安全漏洞。以往需手動編寫轉(zhuǎn)義函數(shù):
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
const text = "Hello (World)";
const regex = new RegExp(escapeRegExp(text), 'g');
ES2025 新增原生方法 RegExp.escape(),一行代碼即可安全轉(zhuǎn)義,避免正則注入風(fēng)險:
const text = "Hello (World)";
const regex = new RegExp(RegExp.escape(text), 'g');
console.log(regex.test("Hello (World)")); // true
瀏覽器支持情況:
正則表達式模式修飾符
ES2025 將允許在正則表達式中動態(tài)啟用或禁用標志(如 i、m、s),使用語法如 (?i:pattern) 或 (?-i:pattern)。
以前,標志只能應(yīng)用于整個正則表達式,無法局部控制。例如,匹配部分不區(qū)分大小寫需要拆分正則或使用復(fù)雜技巧,這大大限制了復(fù)雜模式的表達能力。
在 ES2025 中可以這樣:
const regex = /^(?i:abc)def(?-i:ghi)$/;
console.log(regex.test("AbcDefGHI")); // true
重復(fù)命名捕獲組
ES2025 將允許在正則表達式的不同分支中使用相同的命名捕獲組名稱,只要這些組不會同時匹配。例如,(?<year>\d{4})
可以出現(xiàn)在多個分支中。
以前,命名捕獲組必須唯一,導(dǎo)致匹配不同格式時需要使用不同組名。在訪問結(jié)果時需額外邏輯判斷,復(fù)雜且冗長,限制了正則表達式的靈活性。
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 方法
為內(nèi)置 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 將允許直接導(dǎo)入 JSON 文件,語法:import ... with { type: 'json' };。
以前,導(dǎo)入 JSON 需要借助 fetch 或 fs來實現(xiàn):
fetch('./config.json')
.then(response => response.json())
.then(data => console.log(data));
在 ES2025 中可以這樣:
import config from './config.json' with { type: 'json' };
console.log(config);
導(dǎo)入屬性
在 import 中添加屬性,使用 with 指定模塊類型,如 with { type: 'json' };。
以前,模塊類型由擴展名推斷,可能導(dǎo)致安全問題。
const config = require('./config.json');
在 ES2025 中可以這樣:
import config from './config.json' with { type: 'json' };
TypedArray 增強
Float16Array
添加 Float16Array TypedArray 和相關(guān)方法,支持 16 位浮點數(shù)。
以前,JavaScript 只支持 32 位和 64 位浮點數(shù),16 位浮點數(shù)需庫支持,效率較低。
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
不過,F(xiàn)loat16Array 主要用于圖形和機器學(xué)習(xí),可能在普通開發(fā)中影響有限。