Skip to content

ES12

版本记录

版本介绍

来源: https://262.ecma-international.org/12.0/ Introduction

This specification, the 12th edition, introduces the replaceAll method for Strings; Promise.any, a Promise combinator that short-circuits when an input value is fulfilled; AggregateError, a new Error type to represent multiple errors at once; logical assignment operators (??=, &&=, ||=); WeakRef, for referring to a target object without preserving it from garbage collection, and FinalizationRegistry, to manage registration and unregistration of cleanup operations performed when target objects are garbage collected; separators for numeric literals (1_000); and Array.prototype.sort was made more precise, reducing the amount of cases that result in an implementation-defined sort order.

版本概要

版本特性

String.prototype.replaceAll()

replaceAll() 方法返回一个新字符串,其中所有匹配 pattern 的部分都被替换为 replacement。pattern 可以是一个字符串或一个 RegExp,replacement 可以是一个字符串或一个在每次匹配时调用的函数。原始字符串保持不变。

js
const paragraph = "I think Ruth's dog is cuter than your dog!"

console.log(paragraph.replaceAll('dog', 'monkey'))
// Expected output: "I think Ruth's monkey is cuter than your monkey!"

// Global flag required when calling replaceAll with regex
const regex = /Dog/gi
console.log(paragraph.replaceAll(regex, 'ferret'))
// Expected output: "I think Ruth's ferret is cuter than your ferret!"

Promise.any

Promise.any() 静态方法将一个 Promise 可迭代对象作为输入,并返回一个 Promise。当输入的任何一个 Promise 兑现时,这个返回的 Promise 将会兑现,并返回第一个兑现的值。当所有输入 Promise 都被拒绝(包括传递了空的可迭代对象)时,它会以一个包含拒绝原因数组的 AggregateError 拒绝。

js
const promise1 = Promise.reject(0)
const promise2 = new Promise((resolve) => setTimeout(resolve, 100, 'quick'))
const promise3 = new Promise((resolve) => setTimeout(resolve, 500, 'slow'))

const promises = [promise1, promise2, promise3]

Promise.any(promises).then((value) => console.log(value))

// Expected output: "quick"

WeakRef

WeakRef 对象允许你保留对另一个对象的弱引用,但不会阻止垃圾回收(GC)清理被弱引用的对象。

WeakRef 对象包含对对象的弱引用,这个弱引用被称为该 WeakRef 对象的 target 或者是 referent。对象的弱引用是指该引用不会阻止 GC 回收这个对象。而与此相反的,一个普通的引用(或者说强引用)会将与之对应的对象保存在内存中。只有当该对象没有任何的强引用时,JavaScript 引擎 GC 才会销毁该对象并且回收该对象所占的内存空间。如果上述情况发生了,那么你就无法通过任何的弱引用来获取该对象。

js
class Counter {
  constructor(element) {
    // Remember a weak reference to the DOM element
    this.ref = new WeakRef(element)
    this.start()
  }

  start() {
    if (this.timer) {
      return
    }

    this.count = 0

    const tick = () => {
      // Get the element from the weak reference, if it still exists
      const element = this.ref.deref()

      if (element) {
        element.textContent = ++this.count
      } else {
        // The element doesn't exist anymore
        console.log('The element is gone.')
        this.stop()
        this.ref = null
      }
    }

    tick()
    this.timer = setInterval(tick, 1000)
  }

  stop() {
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = 0
    }
  }
}

const counter = new Counter(document.getElementById('counter'))
counter.start()
setTimeout(() => {
  document.getElementById('counter').remove()
}, 5000)

逻辑赋值运算符

逻辑与赋值(&&=)

逻辑与赋值(x &&= y)运算仅在 x 为真值时为其赋值。

js
let a = 1
let b = 0

a &&= 2
console.log(a)
// Expected output: 2

b &&= 2
console.log(b)
// Expected output: 0

逻辑或赋值(||=)

逻辑或赋值(x ||= y)运算仅在 x 为假值时为其赋值。

js
const a = { duration: 50, title: '' }

a.duration ||= 10
console.log(a.duration)
// Expected output: 50

a.title ||= 'title is empty.'
console.log(a.title)
// Expected output: "title is empty."

逻辑空赋值(??=)

逻辑空赋值运算符(x ??= y)仅在 x 是空值(nullundefined)时对其赋值。

js
const a = { duration: 50 }

a.speed ??= 25
console.log(a.speed)
// Expected output: 25

a.duration ??= 10
console.log(a.duration)
// Expected output: 50

数字分隔符

这个新特性允许在数值字面量中使用下划线(_)作为数字的可视分组,以提高数值的可读性,但它不会改变数值的实际值

js
let budget = 1_000_000_000_000

// What is the value of `budget`? It's 1 trillion!
//
// Let's confirm:
console.log(budget === 10 ** 12) // true