概述
ECMAScript2025于2025年6月26日正式發布, 本文會介紹ECMAScript2025(ES16),即ECMAScript的第16個版本的新特性。
以下摘自官網:ecma-262
ECMAScript 2025, the 16th edition, added a new Iterator global with associated static and prototype methods for working with iterators; added methods to Set.prototype for performing common operations on Sets; added support for importing JSON modules as well as syntax for declaring attributes of imported modules; added the RegExp.escape method for escaping a string to be safely used in a regular expression; added syntax for enabling and disabling modifier flags inline within regular expressions; added the Promise.try method for calling functions which may or may not return a Promise and ensuring the result is always a Promise; and added a new Float16Array TypedArray kind as well as the related DataView.prototype.getFloat16, DataView.prototype.setFloat16, and Math.f16round methods.
ECMAScript2025的新特性如下:
Import
+JSON
- 迭代器輔助方法
Set
實例方法增強- 正則表達式
- 異步處理改進
- 數值表示擴展
Import+JSON
ES2025
引入了import attributes
,用于導入非JavaScript類型的模塊,比如JSON
模塊。
如下:
import config from './config.json' with {type:'json'}
迭代器輔助方法
ES2025
新增同步迭代器輔助函數:為所有同步迭代器添加一系列的輔助方法,比如map
、filter
、some
等,并且支持鏈式調用,可用于鏈式處理可迭代對象的數據,實現惰性求值,避免創建多個中間數組。
Set
實例方法增強
ES2025
為Set
實例添加了如下方法:
intersection
:返回兩個集合的交集union
:返回兩個集合的并集difference
:返回兩個集合的差集symmetricDifference
:返回兩個集合的對稱差集isSubsetOf
:判斷一個集合是否是另一個集合的子集isSupersetOf
:判斷一個集合是否是另一個集合的超集isDisjointFrom
:判斷兩個集合是否沒有交集
正則表達式
ES2025
在正則表達式方面有如下增強:
- 新增
RegExp.escape
方法,可將字符串中的正則元字符進行轉義 - 正則表達式內聯標志
- 重復命名捕獲組
異步處理改進
ES2025
新增了Promise.try()
方法,用于統一封裝同步返回值或拋錯的函數,對于一個可能會拋錯的異常函數,使用Promise.try
可以更方便進行錯誤處理。
數值表示擴展
ES2025
提供對16位浮點數的原生支持,包括Float16Array
、DataView.prototype.getFloat16
/DataView.prototype.setFloat16
以及Math.f16round
方法,這些方法在WebGPU/WebGL中可節省帶寬和內存。
其他特性
- 后置檢查的聲明式控制流:引入
checked{}
和asset
關鍵字 ArrayBuffer
的構造共享數組