概述
ECMAScript2021于2021年6月正式发布, 本文会介绍ECMAScript2021(ES12),即ECMAScript的第12个版本的新特性。
以下摘自官网:ecma-262
ECMAScript 2021, the 12th edition, introduced the replaceAll method for Strings; Promise.any, a Promise combinator that short-circuits when an input value is fulfilled; AggregateError, a new Error type to represent multiple errors at once; logical assignment operators (??=, &&=, ||=); WeakRef, for referring to a target object without preserving it from garbage collection, and FinalizationRegistry, to manage registration and unregistration of cleanup operations performed when target objects are garbage collected; separators for numeric literals (1_000); and Array.prototype.sort was made more precise, reducing the amount of cases that result in an implementation-defined sort order.
ECMAScript2021(ES12)
ES2021
的新特性如下:
String.prototype.replaceAll
Promise.any
AggregateError
WeakRef
和FinalizationRegistry
- 数字字面量分隔符
- 逻辑赋值运算符
Array.prototype.sort
优化
字符串 replaceAll
方法
replaceAll
方法用于替换字符串中所有匹配的子串
const str = 'hello world';
const newStr = str.replaceAll('l', 'L');
console.log(newStr); // 'heLLo worLd'
兼容性

Promise.any
方法
Promise.any
方法接收一个可迭代对象,返回一个Promise
对象。当可迭代对象中的任意一个Promise
对象变为fulfilled
状态时,Promise.any
返回的Promise
对象也会变为fulfilled
状态。如果可迭代对象中的所有Promise
对象都变为rejected
状态,则Promise.any
返回一个包含错误的AggregateError
.
AggregateError
也是ES2021
新增的内容,用于将多个错误合并为一个错误对象,通常用于Promise.any
方法中。
Promise.any
方法和Promise.all
类似,前者是fulfilled
的短路操作,后者是rejected
的短路操作。
const promise1 = Promise.reject('失败1');
const promise2 = Promise.resolve('成功2');
const promise3 = Promise.resolve('成功3');Promise.any([promise1, promise2, promise3]).then(result => console.log(result)) // 输出:"成功2"(第一个兑现的).catch(err => console.log(err));
兼容性

WeakRef
类 与 FinalizationRegistry
类
WeakRef
类用于创建对对象的弱引用,不会阻止对象被垃圾回收(GC)。这与普通的强引用不同——强引用会让对象始终保存在内存中
const obj = { name: 'Alice' };
const weakRef = new WeakRef(obj);
console.log(weakRef.deref()); // { name: 'Alice' }
FinalizationRegistry
类用于注册清理回调函数,当弱引用的对象被垃圾回收时,会调用注册的回调函数。
const registry = new FinalizationRegistry(key => {console.log('对象被垃圾回收', key);
});const obj = { name: 'Alice' };
registry.register(obj, 'obj1');
兼容性


数字字面量分隔符
ES2021
允许在数字字面量中使用下划线_
作为分隔符,提高长数字的可读性
const num1 = 1_000_000; // 等价于 1000000
const num2 = 0.000_001; // 等价于 0.000001
const num3 = 0b1010_1100; // 二进制数字,等价于 0b10101100
兼容性

逻辑赋值运算符
ES2021
引入了逻辑赋值运算符,包括&&=
、||=
和??=
。这些运算符将逻辑运算符和赋值运算符结合起来,使代码更简洁。
&&=
:当左侧值为真值时,才会赋值||=
:当左侧值为假值(false
、null
、0
、''
)时,才赋值??=
:当左侧值为null
或undefined
时,才赋值,(与||=
的区别:不把0
、''
视为 “需要赋值” 的情况
// 旧写法
a = a && b;
a = a || b;
a = a ?? b;// 新写法
a &&= b;
a ||= b;
a ??= b;
兼容性



Array.prototype.sort
优化
之前的 sort
方法在某些情况下(如包含相同元素的数组)可能产生依赖于引擎实现的排序结果。ES2021
规范更精确地定义了排序算法的行为,减少了这种 “实现定义” 的场景,使不同 JavaScript 引擎的排序结果更一致。