概述
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 引擎的排序結果更一致。