逻辑赋值运算符
逻辑赋值运算符📖 .
//"Or Or Equals"
x ||= y;
x || (x = y);
// "And And Equals"
x &&= y;
x && (x = y);
// "QQ Equals"
x ??= y;
x ?? (x = y);
const updateID = user => {
// 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
}
function setOpts(opts) {
opts.cat ??= 'meow'
opts.dog ??= 'bow';
}
setOpts({ cat: 'meow' })
空值合并操作符(??
)是一个逻辑操作符,当左侧的操作数为 null
或者 undefined
时,返回其右侧操作数,否则返回左侧操作数。
数字分隔符
数字组之间的视觉分离📖
1_000_000_000 // 1百万
101_475_938.38
let fee = 123_00; // $123 (12300 cents, apparently)
let fee = 12_300; // $12,300
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
0.000_001 // 一百万分支一
1e10_000 // 10^10000
0xA0_B0_C0; // 16进制也可以这种分隔
Promise.any 和 AggregateError
Promise.any + AggregateError 📖
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.
console.log(first);
// → 'home'
}).catch((error) => {
// All of the promises were rejected.
console.log(error);
});
^ 在上面的例子中error
是一个AggregateError
String.prototype.replaceAll
replaceAll 📖
// String.prototype.replaceAll(searchValue, replaceValue)
'x'.replace('', '_');
// → '_x'
'xxx'.replace(/(?:)/g, '_');
// → '_x_x_x_'
'xxx'.replaceAll('', '_');
// → '_x_x_x_'
WeakRefs 和 FinalizationRegistry 对象
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);