ES12新增内容
大约 2 分钟JavaScriptES12JavaScript
ES12(ECMAScript 2021)新特性
1. String.prototype.replaceAll() 方法
允许在字符串中替换所有匹配的子字符串。之前的 replace() 只会匹配一个。
示例:
const originalString = "apple orange apple banana apple";
const newString = originalString.replaceAll("apple", "fruit");
// newString: 'fruit orange fruit banana fruit'
2. Promise.any() 方法
允许在一组 Promise 中,只要有一个 Fulfilled 状态,就返回该 Promise 的结果。如果全部拒绝,则抛出 AggregateError 异常。
示例:
const delay = (value, ms) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const promises = [
delay('a', 3000),
delay('b', 2000),
delay('c', 4000)
];
Promise.any(promises)
.then(res => console.log(res)) // b
.catch(err => console.error(err.name, err.message, err.errors)); // 全部失败时返回:AggregateError All promises were rejected [ 'a', 'b', 'c' ]
3. 逻辑赋值操作符(Logical Assignment Operators)
引入了 ||=, &&= 和 ??= 这三个逻辑运算符与赋值操作符的组合。
示例:
let a;
a ||= 'default'; // 如果 a 是 falsy,则 a = 'default'
// 等效于
// a || (a = 'default');
// 或者
// if (!a) a = 'default';
a &&= 'override'; // 如果 a 是 truthy,则 a = 'override'
// 等效于
// a && (a = 'override');
// 或者
// if (a) a = 'override';
a ??= 'fallback'; // 如果 a 是 null 或 undefined,则 a = 'fallback'
// 等效于
// a ?? (a = 'fallback');
// 或者
// if (a === undefined || a === null) a = 'fallback';
4. 数字分隔符 _
用于提高数字可读性,不改变数值本身。
示例:
const budget = 1_000_000_000_000;
console.log(budget === 10 ** 12); // true
5. WeakRef 对象
WeakRef 对象包含对对象的弱引用,这个弱引用被称为该 WeakRef 对象的 target 或 referent。当目标对象没有其他强引用时,垃圾回收器可以安全地回收它。
创建和使用 WeakRef 示例:
const obj = { a: 1 };
const ref = new WeakRef(obj);
console.log(ref.deref()); // { a: 1 }
// 如果 obj 被垃圾回收,ref.deref() 将返回 undefined
WeakRef.prototype.deref() 返回当前实例的 WeakRef 对象所绑定的目标对象,如果该目标对象已被垃圾回收则返回 undefined。
