在 ECMAScript2021 中,只有5个新增特性String.prototype.replaceAll、Promise.any、WeakRefs、Logical Assignment Operators、Numeric separators
String.prototype.replaceAll;
在需要替换全部字符的时候,不需要使用带全局 flag 的正则了1
2const queryString = 'q=query+string+parameters';
const withSpaces = queryString.replace(/\+/g, ' ');
变成1
2const queryString = 'q=query+string+parameters';
const withSpaces = queryString.replaceAll('+', ' ');
注意,如果 replaceAll 的第一个参数是一个非全局的正则,那么会抛错。因为 replaceAll 异味着就是替换全局,如果传入一个不带全局flag的正则,那就有这个方法的含义有冲突了,所以抛错。
Promise.any
Promise 终于集齐了这个4个方法Promise.all,Promise.race,Promise.allSettled, Promise.any。1
2
3
4
5
6try {
const first = await Promise.any(promises);
// Any of the promises was fulfilled.
} catch (error) {
// All of the promises were rejected.
}
WeakRefs
19年4月进入stage 3。增加了 WeakRef 和 FinalizationGroup 两个构造函数。优化垃圾收集,避免内存泄漏1
2
3
4
5
6
7
8
9
10// WeakRef
let weakRef = new WeakRef(someObject);
targetOrUndefined = weakRef.deref(); // someObject or undefined
// FinalizationGroup
const registry = new FinalizationRegistry(heldValue => {
// 被垃圾回收时,触发回调
});
registry.register(theObject, "some value");
Logical Assignment Operators
- 逻辑运算和赋值运算合并的一个操作符
- 使用示例
1
2
3
4
5
6
7
8
9
10a ||= b;
a || (a = b);
// "And And Equals"
a &&= b;
a && (a = b);
// "QQ Equals"
a ??= b;
a ?? (a = b);
Numeric separators
2019年提到stage 3时,做过介绍
用下划线(_)做数字分隔符,让数字的可读性更强1
2
3
4
5
6
7
8
9
1_000_000_000 // Ah, so a billion
101_475_938.38 // And this is hundreds of millions
let fee = 123_00; // $123 (12300 cents, apparently)
let fee = 12_300; // $12,300 (woah, that fee!)
let amount = 12345_00; // 12,345 (1234500 cents, apparently)
let amount = 123_4500; // 123.45 (4-fixed financial)
let amount = 1_234_500; // 1,234,500