ES11-2020

1. BigInt

  • BigInt 是一种内置对象,它提供了一种方法来表示大于 2^53 - 1 的整数。BigInt 可以用于任何需要整数的场合:任何接受 Number 类型的地方都可以使用 BigInt 类型。
// 2^53

const theBiggestInt = 9007199254740991n

// 2^64

const alsoHuge = BigInt(9007199254740991)

// 2^2000

const huge = 1234567890123456789012345678901234567890n

// 2^53 - 1

const max = BigInt(Number.MAX_SAFE_INTEGER)

// 2^53

const tooBig = BigInt(Number.MAX_SAFE_INTEGER) + 1n

// SyntaxError: Cannot mix BigInt and other types, use explicit conversions

const alsoHuge = BigInt(9007199254740991)

const bigSum = theBiggestInt + alsoHuge

console.log(bigSum) // 18014398509481982n

console.log(typeof bigSum) // "bigint"

2. Promise.allSettled()

  • Promise.allSettled() 方法返回一个在所有给定的 promise 都已经 fulfilled 或 rejected 后的 promise,并带有一个对象数组,每个对象表示对应的 promise 结果。
const promises = [Promise.resolve(1), Promise.reject(2), Promise.resolve(3)]

Promise.allSettled(promises).then((results) => {
  console.log(results)
  // [
  //   { status: 'fulfilled', value: 1 },
  //   { status: 'rejected', reason: 2 },
  //   { status: 'fulfilled', value: 3 }
  // ]
})

3. Optional Chaining

  • 可选链操作符(?.)可用于访问嵌套对象的属性,而不必明确验证链中的每个引用是否有效。可选链操作符有两种形式:?. 和 ?.[ ]。当 ?. 出现在表达式的左侧时,它被称为可选链的“删除”操作符。当 ?. 或 ?.[ ] 出现在表达式的右侧时,它被称为可选链的“保留”操作符。
// 1. ?. 保留操作符

// 2. ?.[] 保留操作符

// 3. ?.() 保留操作符

// 4. ?. 与 delete 操作符

// 5. ?. 与赋值操作符

// 6. ?. 与逻辑操作符

// 7. ?. 与逗号操作符

4. Nullish Coalescing Operator

  • 空值合并操作符(??)返回它的第一个运算数,如果该运算数是 null 或 undefined,否则返回第二个运算数。
// 1. ?? 优先级高于 ||

// 2. ?? 只有左侧为 null 或 undefined 时才会返回右侧

// 3. ?? 不会对左侧的值进行转换

// 4. ?? 不会对右侧的值进行转换

// 5. ?? 右侧可以是一个表达式

// 6. ?? 右侧可以是一个函数

// 7. ?? 右侧可以是一个对象

// 8. ?? 右侧可以是一个数组

// 9. ?? 右侧可以是一个正则表达式

// 10. ?? 右侧可以是一个类

// 11. ?? 右侧可以是一个对象

5. Dynamic Import

  • 动态 import() 表达式是一个 ECMAScript 提案,它允许模块按需加载。它是一个类似于 import 语句的表达式,但是它可以在运行时动态地指定模块的路径。
// 1. 动态导入模块

import { add } from './math.js'

console.log(add(16, 26)) // 42

// 2. 动态导入模块

import('./math.js').then((math) => {
  console.log(math.add(16, 26)) // 42
})

6. import.meta

  • import.meta 对象提供了关于当前模块的信息。它的属性和方法取决于模块的类型。
// 1. import.meta.url

// 2. import.meta.resolve()

// 3. import.meta.glob()

// 4. import.meta.globEager()

// 5. import.meta.hot

// 6. import.meta.env

// 7. import.meta.webpackHot

7. 字符串方法 matchAll()

  • String.prototype.matchAll() 方法返回一个包含所有匹配正则表达式及分组捕获结果的迭代器。
const str = 'test1test2'

const regexp = /t(e)(st(\d?))/g

const matches = str.matchAll(regexp)

for (const match of matches) {
  console.log(match)
  // ["test1", "e", "st1", "1", index: 0, input: "test1test2", groups: undefined]
}

// expected output: Array ["test1", "e", "st1", "1"]

// expected output: Array ["test2", "e", "st2", "2"]

8. 模块复合

  • 模块复合(module concatenation)是一种新的优化技术,它允许将多个模块合并为一个模块,以减少浏览器加载的文件数量。
export * from './module1.js'

// 相当于
import * as _module1 from './module1.js'
export { _module1 as module1 }