新特性预览

  • String.prototype.replaceAll( )
  • 私有方法 Private Methods 与私有访问者 Private Accessors
  • Promise.any 与 AggregateError
  • WeakRefs 弱引用
  • 逻辑运算符和赋值表达式
  • Numeric separators

String.prototype.replaceAll( )

以前我们想全部替换某个字符串内部字符,则需要 String.prototype.replaceregexp 来配合使用

const str = "i am a test string";

// before
str.replace(/a/g, "")
console.log(str)
// "i m  test string"

// now
str.replaceAll("a", "")
console.log(str)
// "i m  test string"

Promise.any

Promise列表中的任意一个promise成功resolve则返回第一个resolve的结果状态, 如果所有的promisereject,则抛出异常表示所有请求失败

// 官方提供例子-检测哪个网站更快
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);
});

Private Methods

私有方法只能在定义它的类内部访问,专用方法名称以开头#

class Person {
    age=18
    #setAge(age){
        this.age = age
    }
}
const p = new Person()
p.setAge(20) // TypeError: p.setAge is not a function

逻辑运算符和赋值表达式

a ||= b
//等价于
a = a || (a = b)

a &&= b
//等价于
a = a && (a = b)

a ??= b
//等价于
a = a ?? (a = b)
  • a ||= b:当a值不存在时,将b变量赋值给a
  • a &&= b:当a值存在时,将b变量赋值给a
  • a ??= b:当a值为null或者undefined时,将b变量赋值给a

Numeric separators

数字的可读性随着数字长度的增加而降低。现在,则可以使用下划线 _ 来分隔数字组,使得长数字更加清晰可读。

const num1 = 123456789
const num2 = 123_456_789

console.log(num1 === num2)
// true

目录