ES12 (ES2021) 速查代码片(可直接复制使用)

1 阅读1分钟

ES12 (ES2021) 速查代码片(可直接复制使用)

1. 逻辑赋值运算符

// ||=  为假时赋值
let a = '';
a ||= '默认值';

// &&=  为真时赋值
let b = 10;
b &&= b + 1;

// ??=  仅 null/undefined 时赋值(推荐)
let c = null;
c ??= 18;

2. String.replaceAll()

const str = 'a-b-a-b';
const res = str.replaceAll('a', '*');
// "* - b - * - b"

3. 数字分隔符 _

const num = 1_000_000_000; // 10亿
const price = 99_99;       // 99.99
const binary = 0b1010_1111;

4. Promise.any()

const p1 = Promise.reject('err1');
const p2 = Promise.resolve('ok2');
const p3 = Promise.reject('err3');

Promise.any([p1, p2, p3])
  .then(console.log)
  .catch(err => console.log(err.errors));

5. WeakRef & FinalizationRegistry

// 弱引用
const obj = { name: 'test' };
const wr = new WeakRef(obj);
obj = null;
console.log(wr.deref()); // 可能 undefined

// 垃圾回收回调
const registry = new FinalizationRegistry(msg => {
  console.log('对象被回收:', msg);
});
const o = {};
registry.register(o, '清理资源');
o = null;

6. 私有类字段

class Person {
  #age = 18;
  getAge() { return this.#age; }
}

const p = new Person();
console.log(p.getAge()); // 18
// p.#age → 报错

7. Intl.DateTimeFormat 简化写法

const date = new Date();
const fmt = new Intl.DateTimeFormat('zh-CN', {
  dateStyle: 'medium',
  timeStyle: 'short'
});
console.log(fmt.format(date));

8. 安全的空值判断合集

// 默认值推荐用 ??
const config = { timeout: 0 };
const timeout = config.timeout ?? 5000; // 0 保留

// 替代 ||
const title = config.title ?? '无标题';

如果你想要一页A4可打印版配套练习题,我也可以给你整理。