概述
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
的构造共享数组