Skip to main content

ES2018

ES2018 增强了异步处理能力,并将解构与延展操作符扩展到了对象。

1. 对象的 Rest/Spread 属性

允许我们在对象字面量中使用扩展运算符(...)和剩余属性(Rest)。这极大地简化了对象的浅拷贝和属性合并/剔除。

const { a, b, ...rest } = { a: 1, b: 2, c: 3, d: 4 };
console.log(rest); // { c: 3, d: 4 }

const obj2 = { ...rest, e: 5 }; // { c: 3, d: 4, e: 5 }

2. Promise.finally()

无论 Promise 的最终状态是 resolved 还是 rejected.finally() 中的回调函数都会被执行。常用于清理操作(如关闭 loading 动画、释放资源)。

fetch('/api/data')
.then(res => res.json())
.catch(err => console.error(err))
.finally(() => {
isLoading = false; // 无论成功失败都会执行
});

3. 异步迭代 (for-await-of)

提供了一种按顺序遍历异步可迭代对象(如多个 Promise 或 Async Generator)的方式。

async function process(promises) {
for await (const result of promises) {
console.log(result);
}
}

4. 正则表达式增强

  • 命名捕获组 (Named Capture Groups):允许给正则表达式的捕获组命名,通过 ?<name> 语法,使得结果可以通过名字而不是索引访问。
    const reg = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
    const match = reg.exec('2023-10-01');
    console.log(match.groups.year); // "2023"
  • dotAll 模式 (/s 标志):默认情况下,正则表达式中的 . 不能匹配换行符(\n 等)。加上 /s 标志后,. 可以匹配任意字符,包括换行符。
  • 反向断言 (Lookbehind Assertions):支持向后查找匹配,如 (?<=...)(正向)和 (?<!...)(负向)。
  • Unicode 属性转义:允许使用 \p{...}\P{...} 来匹配符合特定 Unicode 属性的字符。