异步迭代(Async Iteration)

Run
async function iteration() {
  const times = [2000, 1000, 3000, 2000];
  const delay = (time) =>
    new Promise((resolve) => setTimeout(() => resolve(time), time));
  for await (const time of times.map(delay)) {
    console.log(time);
  }
}
iteration();

promise.finally()

无论Promise运行成功与否,finally都会触发。

Run
new Promise((resolve, reject) => {
  reject(new Error('rejected!'));
})
  .then((res) => {
    return res;
  })
  .finally(() => {
    console.log('Promise finished.');
  });

Object Rest 参数/Spread 扩展运算符

ES6 引入了数组的 Rest 参数及 Spread 扩展运算符。ES9 为对象结构提供了与数组相同的Rest 参数及 Spread 扩展运算符。扩展运算符可以浅拷贝一个对象。

Run
const obj = { foo: 'foo', bar: 'bar', baz: 'baz' };
const { foo, ...rest } = obj;
console.log(rest);

const spread = { ...obj, a: 1, b: 2, c: 3 };
console.log(spread);

正则表达式扩展

命名捕获组

使用命名捕获组符号?<name>进行捕获。任何匹配失败的命名组都将返回undefined

Run
const reDate = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/;
const match = reDate.exec('2018-04-30');
console.log({ ...match.groups });

反向断言

Run
// 先行断言 lookahead
const [sign] = /\D(?=\d+)/.exec('¥1234.56');
console.log(sign);
// ¥

// 肯定反向断言 lookbehind
const [sign1] = /(?<=\D)\d+/.exec('¥1234.56');
console.log(sign1);
// 1234.56

// 否定反向断言 neglookbehind
const [sign2] = /(?<!\D)\d+/.exec('¥1234.56');
console.log(sign2);
// 234

dotAll 模式

正则表达式中.匹配除回车外的任何单字符,标记s允许行终止符的出现。

Run
console.log(/what.the.heck/.test('what\nthe\nheck'));
// false
console.log(/what.the.heck/s.test('what\nthe\nheck'));
// true

Unicode 转义

ES9 添加了对 Unicode 属性的转义:\p{...}\P{...}。在正则表达式中使用u标记,并\p/\P中以键值对方式设置需要匹配的属性而非具体内容。此特性可以避免使用特定 Unicode 区间来进行内容类型判断,提升可读性和可维护性。

Run
console.log(/\p{Script=Greek}/u.exec('π'));
// true

非转义序列的模板字符串 (参考open in new window)