ECMAScript2021(ES12)新特性
# 概述
ECMAScript2021于2021年6月正式发布, 本文会介绍ECMAScript2021(ES12),即ECMAScript的第12个版本的新特性。
以下摘自官网:ecma-262 (opens new window)
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.replaceAllPromise.anyAggregateErrorWeakRef和FinalizationRegistry- 数字字面量分隔符
- 逻辑赋值运算符
Array.prototype.sort优化
# 字符串 replaceAll方法
replaceAll方法用于替换字符串中所有匹配的子串
const str = 'hello world';
const newStr = str.replaceAll('l', 'L');
console.log(newStr); // 'heLLo worLd'
2
3
# 兼容性
# 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));
2
3
4
5
6
7
# 兼容性
# WeakRef类 与 FinalizationRegistry类
WeakRef类用于创建对对象的弱引用,不会阻止对象被垃圾回收(GC)。这与普通的强引用不同——强引用会让对象始终保存在内存中
const obj = { name: 'Alice' };
const weakRef = new WeakRef(obj);
console.log(weakRef.deref()); // { name: 'Alice' }
2
3
FinalizationRegistry类用于注册清理回调函数,当弱引用的对象被垃圾回收时,会调用注册的回调函数。
const registry = new FinalizationRegistry(key => {
console.log('对象被垃圾回收', key);
});
const obj = { name: 'Alice' };
registry.register(obj, 'obj1');
2
3
4
5
6
# 兼容性
# 数字字面量分隔符
ES2021允许在数字字面量中使用下划线_作为分隔符,提高长数字的可读性
const num1 = 1_000_000; // 等价于 1000000
const num2 = 0.000_001; // 等价于 0.000001
const num3 = 0b1010_1100; // 二进制数字,等价于 0b10101100
2
3
# 兼容性
# 逻辑赋值运算符
ES2021引入了逻辑赋值运算符,包括&&=、||=和??=。这些运算符将逻辑运算符和赋值运算符结合起来,使代码更简洁。
&&=:当左侧值为真值时,才会赋值||=:当左侧值为假值(false、null、0、'')时,才赋值??=:当左侧值为null或undefined时,才赋值,(与||=的区别:不把0、''视为 “需要赋值” 的情况
// 旧写法
a = a && b;
a = a || b;
a = a ?? b;
// 新写法
a &&= b;
a ||= b;
a ??= b;
2
3
4
5
6
7
8
9
# 兼容性
# Array.prototype.sort优化
之前的 sort 方法在某些情况下(如包含相同元素的数组)可能产生依赖于引擎实现的排序结果。ES2021 规范更精确地定义了排序算法的行为,减少了这种 “实现定义” 的场景,使不同 JavaScript 引擎的排序结果更一致。
- 01
- Pinia中实现监听action的原理11-28
- 03
- patch中的双端比较快速算法09-25