逻辑赋值操作符

  • 逻辑赋值操作符将逻辑操作(&&、|| 或 ??)与赋值表达式组合在一起。
  1. 带有 || 的逻辑赋值操作
let y = 1

x ||= y;
console.log(x) // 1
console.log(y) // 1

let x = 1
let y = 2

x ||= y;
console.log(x) // 1
console.log(y) // 2


  1. 带有 && 的逻辑赋值操作
let x = 1
let y = 2

x &&= y
console.log(x) // 2
console.log(y) // 2

let x = 0
let y = 2

x &&= y
console.log(x) // 0
console.log(y) // 2


  1. 带有 ?? 的逻辑赋值操作符
let x
let y = 2

x ??= y
console.log(x) // 2

let x = 1
let y = 2

x ??= y
console.log(x) // 1


数字分隔符,只是为了增加可读性,所以可以放在数字内的任何地方

const num = 100_000_000
console.log(num) // 100000000

const num_f = 100_000_000.123456
console.log(num_f) // 100000000.123456

const num_2 = 0b101001
console.log(num_2) // 41

const numbig = 100_000_000_000n
console.log(numbig) // 100000000000n
console.log(numbig.toString()) // 100000000000


Promise.any 与 AggregateError

  • Promise.any()返回第一个完成的promise的值
  • 如果所有传递给Promise.any()作为参数(作为数组)的Promise都被拒绝,则抛出一个"AggregateError"异常。
const p1 = new Promise((resolve, reject) => {
setTimeout(() => resolve('A'), Math.floor(Math.random() * 1000))
})

const p2 = new Promise((resolve, reject) => {
setTimeout(() => resolve('B'), Math.floor(Math.random() * 1000))
})

const p3 = new Promise((resolve, reject) => {
setTimeout(() => resolve('C'), Math.floor(Math.random() * 1000))
});

(async function() {
const result = await Promise.any([p1, p2, p3]);
console.log(result)
})(); // A 或 B 或 C

const p = new Promise((resolve ,reject) => reject());

try {
(async function() {
const result = await Promise.any([p])
console.log(result)
})();
} catch(error) {
console.log(error) // Uncaught (in promise) AggregateError: All promises were rejected
}


String.prototype.replaceAll 方法

  • String.prototype.replaceAll()允许我们用一个不同的值替换字符串中的所有子串实例,而不需要使用全局正则表达式。
const str = "Backbencher sits at the Back"
const newstr = str.replaceAll("Back", "Front")
const newstr1 = str.replace(/Back/g, "Front")
const newstr2 = str.replace("Back", "Front")
console.log(newstr) // Frontbencher sits at the Front
console.log(newstr1) // Frontbencher sits at the Front
console.log(newstr2) // Frontbencher sits at the Back