主要有几个新特性:
Logical Assignment Operators (逻辑分配运算符)
//"Or Or Equals"
x ||= y;
x || (y = z);
// "And And Equals"
x &&= y;
x && (y = z);
// "QQ Equals"
x ??= y;
x ?? (y = z);
以前的代码可以写的更加简洁:
// We can do this
if (!user.id) user.id = 1
// Or this
user.id = user.id || 1
// Or use logical assignment operator.
user.id ||= 1
Numeric Separators(数值分割符)
可以使用_
分割数值,可读性更好
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
Promise.any and AggregateError
在所有请求都出错时才被 rejected
Promise.any([
fetch('https://v8.dev/').then(() => 'home'),
fetch('https://v8.dev/blog').then(() => 'blog'),
fetch('https://v8.dev/docs').then(() => 'docs')
]).then(
(first) => {
// Any of the promises was fulfilled.
},
(error) => {
// All of the promises were rejected.
}
);
String.prototype.replaceAll
增加 String 新方法 replaceAll
'xxx'.replaceAll('', '_');
// → '_x_x_x_'
WeakRefs and FinalizationRegistry Objects
增加 WeakRefs
和 FinalizationRegistry
对象:
let target = {};
let wr = new WeakRef(target);
//wr and target aren't the same
// Creating a new registry
const registry = new FinalizationRegistry(heldValue => {
// ....
});
registry.register(myObject, "some value", myObject);
// ...some time later, if you don't care about `myObject` anymore...
registry.unregister(myObject);
FinalizationRegistry 不懂的同学可以看下:MDN FinalizationRegistry。这两个主要用了做内存管理,日常开发应该比较少见,规范可见:managing-memory
详见:ecma262