Skip to content

ECMAScript 2020 (11)

特性一览

BigInt

BigInt 是一种内置对象,它提供了一种方法来表示大于2^53 - 1的整数。BigInt 可以表示任意大的整数。

普通 Number:

js
9007199254740992 === 9007199254740993; // true

使用 bigint(在整数的末尾追加 n):

js
BigInt(9007199254740992); // 9007199254740992n
9007199254740992n === 9007199254740993n; // false
typeof 9007199254740992n; // bigint

String.matchAll()

返回一个包含所有匹配正则表达式的结果及分组捕获组的迭代器。

分组捕获: [test+数字,e,st+数字,数字]

js
const regexp = /t(e)(st(\d?))/g;
const str = "test1test2";
const array = [...str.matchAll(regexp)];
array[0]; //Array ["test1", "e", "st1", "1"]
array[1]; // Array ["test2", "e", "st2", "2"]

globalThis

ES2020 新增的一个全局对象,它提供了一个标准化的、跨平台的方式来访问全局对象。

在不同的环境中,全局对象的名称可能不同,例如在浏览器中是 window,在 Node.js 中是 global,在 Web Worker 中是 self 等等。

js
// 在浏览器中
globalThis === window; // true

// 在 Node.js 中
globalThis === global; // true

// 在 Web Worker 中
globalThis === self; // true

globalThis 对象上还包含常用的全局属性和函数,例如 console、setTimeout、setInterval、Promise 等等。

js
globalThis.console.log("Hello world!");
globalThis.setTimeout(() => {
  console.log("After 1 second");
}, 1000);

在使用 globalThis 时需要注意的是它只在支持 ES2020 的环境中才能使用,如果在不支持的环境中使用将会抛出异常。因此需要使用适当的 polyfill 或者进行特定的兼容性检测来确保代码可以在不同环境中正常运行。

空值合并操作符

当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。

js
const foo = null ?? "default string";
foo; // "default string"

const baz = 0 ?? 42;
baz; // 0

可选链操作符

在 ECMAScript2020 以前,访问对象的深嵌套属性时,首先需要检查它的上一个属性是否存在,然后才能获取属性的值

ECMAScript2020 提出可选链操作符?.,可以判断操作符之前属性是否有效,从而链式读取对象的属性或返回 undefined

js
const adventurer = {
  name: "Alice",
  cat: {
    name: "Dinah",
  },
};
adventurer.dog?.name; // undefined
adventurer.someNonExistentMethod?.(); // undefined

Promise.allSettled()

Promise.all 具有并发执行异步任务的能力。但如果参数中的任何一个promisereject的话,则整个Promise.all调用会立即终止,并返回一个reject的新的 Promise对象。

Promise.allSettledPromise.all类似, 唯一的不同在于, 不管是否处理成功,都可以拿到每个Promise的状态。

js
const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) =>
  setTimeout(reject, 100, "foo")
);
// "fulfilled"
// "rejected"
Promise.allSettled([promise1, promise2]).then((results) =>
  results.forEach((result) => console.log(result.status))
);

动态 import

标准用法的 import 导入的模块是静态的,会使所有被导入的模块,在加载时就被编译

关键字 import 可以像调用函数一样来动态的导入模块。以这种方式调用,将返回一个 promise。

动态导入

js
const main = document.querySelector("main");
for (const link of document.querySelectorAll("nav > a")) {
  link.addEventListener("click", (e) => {
    e.preventDefault();
    import("/modules/my-module.js") 
      .then((module) => {
        module.loadPageInto(main);
      })
      .catch((err) => {
        main.textContent = err.message;
      });
  });
}

这种使用方式也支持 await 关键字。

js
let module = await import("/modules/my-module.js");