推荐答案
ES12(ES2021)中新增了以下特性:
String.prototype.replaceAll
允许替换字符串中所有匹配的子字符串,而不仅仅是第一个匹配项。Promise.any
接受一个 Promise 数组,返回第一个成功解析的 Promise 结果。如果所有 Promise 都被拒绝,则抛出一个 AggregateError。逻辑赋值运算符
新增了&&=、||=和??=逻辑赋值运算符,简化了条件赋值操作。WeakRefs
允许创建对对象的弱引用,不会阻止垃圾回收器回收对象。FinalizationRegistry
允许在对象被垃圾回收时执行清理操作。数字分隔符
允许在数字中使用下划线_作为分隔符,提高可读性。Intl.ListFormat
提供了一种格式化列表的方式,支持多种语言和地区。Intl.DateTimeFormat 的 dateStyle 和 timeStyle 选项
允许更简单地格式化日期和时间。
本题详细解读
1. String.prototype.replaceAll
在 ES12 之前,String.prototype.replace 只能替换第一个匹配的子字符串。如果需要替换所有匹配项,必须使用正则表达式并加上全局标志 g。ES12 引入了 replaceAll 方法,可以直接替换所有匹配项。
const str = "hello world hello";
console.log(str.replaceAll("hello", "hi")); // 输出: "hi world hi"2. Promise.any
Promise.any 接受一个 Promise 数组,并返回第一个成功解析的 Promise 结果。如果所有 Promise 都被拒绝,则抛出一个 AggregateError,其中包含所有拒绝的原因。
// www.javascriptcn.com code example
const promises = [
Promise.reject("Error 1"),
Promise.resolve("Success 1"),
Promise.reject("Error 2")
];
Promise.any(promises)
.then(result => console.log(result)) // 输出: "Success 1"
.catch(error => console.log(error));3. 逻辑赋值运算符
ES12 引入了三个新的逻辑赋值运算符:&&=、||= 和 ??=,用于简化条件赋值操作。
&&=:仅在左侧值为真时赋值。||=:仅在左侧值为假时赋值。??=:仅在左侧值为null或undefined时赋值。
let a = 1; let b = 0; let c = null; a &&= 2; // a = 2 b ||= 2; // b = 2 c ??= 3; // c = 3
4. WeakRefs
WeakRef 允许创建对对象的弱引用,这意味着即使对象被弱引用,垃圾回收器仍然可以回收该对象。这在某些场景下非常有用,比如缓存。
let obj = { name: "John" };
const weakRef = new WeakRef(obj);
console.log(weakRef.deref()); // 输出: { name: "John" }
obj = null; // 解除强引用
// 垃圾回收后,weakRef.deref() 可能返回 undefined5. FinalizationRegistry
FinalizationRegistry 允许在对象被垃圾回收时执行清理操作。这对于管理资源或执行一些清理任务非常有用。
const registry = new FinalizationRegistry(heldValue => {
console.log(`Cleaning up: ${heldValue}`);
});
let obj = {};
registry.register(obj, "some value");
obj = null; // 解除引用,垃圾回收后触发清理6. 数字分隔符
ES12 允许在数字中使用下划线 _ 作为分隔符,以提高数字的可读性。
const billion = 1_000_000_000; console.log(billion); // 输出: 1000000000
7. Intl.ListFormat
Intl.ListFormat 提供了一种格式化列表的方式,支持多种语言和地区。
const list = ["Apple", "Banana", "Orange"];
const formatter = new Intl.ListFormat("en", { style: "long", type: "conjunction" });
console.log(formatter.format(list)); // 输出: "Apple, Banana, and Orange"8. Intl.DateTimeFormat 的 dateStyle 和 timeStyle 选项
Intl.DateTimeFormat 新增了 dateStyle 和 timeStyle 选项,允许更简单地格式化日期和时间。
const date = new Date();
const formatter = new Intl.DateTimeFormat("en", { dateStyle: "full", timeStyle: "long" });
console.log(formatter.format(date)); // 输出: "Friday, October 13, 2023 at 12:34:56 PM GMT+8"