ES2020 都有哪些新写法?

131 阅读1分钟

1、可选链操作符

// 传统写法
const street = user && user.address && user.address.street;

// ES2020
const street = user?.address?.street; // 任意一环不存在则返回 undefined

支持的场景:

  • 属性访问 obj?.prop
  • 动态属性 obj?.[expr]
  • 函数调用 func?.()

2、空值合并运算符

作用:精准判断 null/undefined(不包含其他假值如 0 或 '')。

// 传统写法
const value = input !== null && input !== undefined ? input : 'default';

// ES2020
const value = input ?? 'default'; // 仅在 input 为 null/undefined 时生效

对比 ||

const count = 0;
console.log(count || 10); // 10(0 是假值)
console.log(count ?? 10); // 0(精准判断)

3、动态导入

作用:按需异步加载模块。

// 传统静态导入
import module from 'module';

// ES2020 动态导入
button.addEventListener('click', async () => {
  const module = await import('./module.js');
  module.doSomething();
});

4、 BigInt 大整数类型

作用:表示超出 Number.MAX_SAFE_INTEGER 的整数。

Number.MAX_SAFE_INTEGER 是多少?

2^53 - 1 = 9007199254740991

技术背景:

JS使用 IEEE 754 标准的64位双精度浮点数表示所有数字(包括整数) 其中52位用于表示整数部分的尾数

5、Promise.allSettled()

获取所有Promise的结果(无论成功还是失败)

6、String.matchAll()

作用:高效遍历正则匹配的所有分组。

const str = 'test1test2';
const regex = /t(e)(st(\d?))/g;

// 传统写法:循环 exec
// ES2020
const matches = [...str.matchAll(regex)];
matches[0]; // ["test1", "e", "st1", "1", index: 0, ...]

七、globalThis

作用:统一全局对象访问(跨浏览器/Node.js 环境)。

// 传统环境判断
const global = typeof window !== 'undefined' ? window : global;

// ES2020
console.log(globalThis); // 浏览器: window, Node.js: global

八、模块新特性

1. import.meta

console.log(import.meta.url); // 文件 URL(如 "file:///path/to/module.js")

2. 导出命名空间

export * as utils from './utils.js'; // 将模块所有导出作为命名空间

九、for-in 机制标准化

明确规范 for-in 循环的遍历顺序(虽实际仍依赖引擎实现)