ECMAScript 2018(ES9)
2025-02-20 20:00
2025-02-22 12:20
核心特性
1. 异步迭代 Asynchronous Iteration
通过 for-await...of
循环遍历异步数据流,结合 async generator 函数生成异步可迭代对象。(如分页 API、文件流)
async function* asyncGenerator() {
yield await Promise.resolve(1);
yield await Promise.resolve(2);
}
(async () => {
for await (const num of asyncGenerator()) {
console.log(num); // 依次输出 1, 2
}
})();
2. Promise.prototype.finally()
无论 Promise 成功或失败,都会执行的回调函数,允许开发者在 Promise 执行完毕后执行一些清理工作(如关闭加载状态、断开连接)。
fetch("https://api.example.com/data")
.then(data => process(data))
.catch(error => log(error))
.finally(() => {
console.log("请求结束");
});
3. 正则表达式增强
- 命名捕获组(Named Capture Groups)
const regex = /(?<year>\d{4})-(?<month>\d{2})/;
const match = regex.exec("2023-10");
console.log(match.groups.year); // "2023"
- 反向断言(Lookbehind Assertions)
//(?<=...) 正向反向断言(匹配前面是某模式的位置)。
//(?<!...) 负向反向断言(匹配前面不是某模式的位置)。
console.log(/(?<=\$)\d+/.exec("$100")[0]); // "100"(匹配以$开头的数字)
- Unicode 属性转义(Unicode Property Escapes)
// 匹配所有字母
const regex = /\p{Script=Greek}/u;
console.log(regex.test("π")); // true(希腊字母)
- dotAll 模式(s 标志):
// 使 . 匹配任意字符(包括换行符)。
console.log(/hello.world/s.test("hello\nworld")); // true
总结
ECMAScript 2018(ES9)进一步完善了 JavaScript 的异步编程模型(如异步迭代),增强了对象和正则的操作能力,并提供了更友好的错误处理机制(finally)。其特性广泛应用于实时数据流处理(如 WebSocket)、状态管理(如 Redux 的不可变更新)及国际化文本解析,标志着 JavaScript 在复杂应用场景下的成熟度提升。后续版本(如 ES2019 的 Array.flat())延续了这一精细化改进的趋势。
评论区
评论区寄了
文章目录
核心特性
1. 异步迭代 Asynchronous Iteration
2. Promise.prototype.finally()
3. 正则表达式增强
总结