推荐答案
ES9(ES2018)中新增的主要特性包括:
- 异步迭代器(Asynchronous Iteration):引入了
for-await-of循环,允许在异步操作中使用迭代器。 - Rest/Spread 属性:扩展了对象解构和对象字面量的功能,支持
...操作符用于对象。 - Promise.prototype.finally():为 Promise 添加了
finally方法,无论 Promise 成功或失败都会执行。 - 正则表达式改进:
- 命名捕获组(Named Capture Groups):允许为正则表达式的捕获组命名。
- 反向断言(Lookbehind Assertions):支持在正则表达式中使用
(?<=...)和(?<!...)进行反向断言。 - Unicode 属性转义(Unicode Property Escapes):允许在正则表达式中使用
\p{...}和\P{...}来匹配 Unicode 字符属性。
- 模板字符串修订:允许在模板字符串中使用未转义的序列。
本题详细解读
1. 异步迭代器(Asynchronous Iteration)
ES9 引入了 for-await-of 循环,允许在异步操作中使用迭代器。这对于处理异步数据流(如从数据库或网络请求中获取数据)非常有用。
async function processAsyncData(asyncIterable) {
for await (const data of asyncIterable) {
console.log(data);
}
}2. Rest/Spread 属性
ES9 扩展了对象解构和对象字面量的功能,支持 ... 操作符用于对象。这使得在对象中合并或提取属性变得更加方便。
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, ...obj1 }; // { c: 3, a: 1, b: 2 }
const { a, ...rest } = obj2; // a = 1, rest = { c: 3, b: 2 }3. Promise.prototype.finally()
finally 方法允许在 Promise 无论成功或失败时都执行一段代码。这对于清理资源或执行一些无论结果如何都需要完成的操作非常有用。
fetch('https://example.com')
.then(response => response.json())
.catch(error => console.error(error))
.finally(() => console.log('Request completed'));4. 正则表达式改进
命名捕获组(Named Capture Groups)
命名捕获组允许为正则表达式的捕获组命名,使得代码更具可读性。
const regex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const match = regex.exec('2023-10-05');
console.log(match.groups.year); // 2023反向断言(Lookbehind Assertions)
反向断言允许在正则表达式中使用 (?<=...) 和 (?<!...) 进行反向匹配。
const regex = /(?<=\$)\d+/;
const match = regex.exec('$100');
console.log(match[0]); // 100Unicode 属性转义(Unicode Property Escapes)
Unicode 属性转义允许在正则表达式中使用 \p{...} 和 \P{...} 来匹配 Unicode 字符属性。
const regex = /\p{Script=Greek}/u;
const match = regex.test('α'); // true5. 模板字符串修订
ES9 允许在模板字符串中使用未转义的序列,这在某些情况下可以简化代码。
const str = String.raw`\u{61}`; // \u{61}
console.log(str); // \u{61}