ECMAScript2025(ES16)新特性

发布于:2025-08-03 ⋅ 阅读:(16) ⋅ 点赞:(0)

概述

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新增同步迭代器辅助函数:为所有同步迭代器添加一系列的辅助方法,比如mapfiltersome等,并且支持链式调用,可用于链式处理可迭代对象的数据,实现惰性求值,避免创建多个中间数组。

Set实例方法增强

ES2025Set实例添加了如下方法:

  • intersection:返回两个集合的交集
  • union:返回两个集合的并集
  • difference:返回两个集合的差集
  • symmetricDifference:返回两个集合的对称差集
  • isSubsetOf:判断一个集合是否是另一个集合的子集
  • isSupersetOf:判断一个集合是否是另一个集合的超集
  • isDisjointFrom:判断两个集合是否没有交集
正则表达式

ES2025在正则表达式方面有如下增强:

  1. 新增RegExp.escape方法,可将字符串中的正则元字符进行转义
  2. 正则表达式内联标志
  3. 重复命名捕获组
异步处理改进

ES2025新增了Promise.try()方法,用于统一封装同步返回值或抛错的函数,对于一个可能会抛错的异常函数,使用Promise.try可以更方便进行错误处理。

数值表示扩展

ES2025提供对16位浮点数的原生支持,包括Float16ArrayDataView.prototype.getFloat16/DataView.prototype.setFloat16以及Math.f16round方法,这些方法在WebGPU/WebGL中可节省带宽和内存。

其他特性
  1. 后置检查的声明式控制流:引入checked{}asset关键字
  2. ArrayBuffer的构造共享数组