一、异步迭代(for-await-of
)
-
支持在异步循环中遍历
Promise
或AsyncIterable
对象(如数据库流、分页 API)。async function processAsyncData(asyncIterable) { for await (const data of asyncIterable) { console.log(data); } }
二、 Promise.prototype.finally()
-
无论
Promise
成功或失败,都会执行的回调(类似try/catch/finally
)。fetch('https://api.example.com/data') .then(response => response.json()) .catch(error => console.error(error)) .finally(() => console.log('请求结束')); // 无论成功失败都会执行
典型用途:
-
关闭加载动画
-
清理资源
三、Rest/Spread 属性(对象扩展)
-
对象剩余参数(Rest):收集剩余属性到新对象。
-
对象扩展(Spread):合并对象(浅拷贝)。
// 对象剩余参数(Rest) const { x, y, ...rest } = { x: 1, y: 2, z: 3, a: 4 }; console.log(rest); // { z: 3, a: 4 } // 对象扩展(Spread) const obj1 = { a: 1 }; const obj2 = { ...obj1, b: 2 }; // { a: 1, b: 2 }
对比数组的 ...
:
-
ES6 已支持数组的 Rest/Spread,ES2018 扩展到对象。
四、正则表达式增强
(1)命名捕获组(Named Capture Groups)
-
用
?<name>
给正则匹配分组命名,提高可读性。const regex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/; const match = regex.exec('2023-10-05'); console.log(match.groups.year); // "2023"
(2)反向断言(Lookbehind Assertions)
-
(?<=...)
正向反向断言(匹配前面是某模式的内容)。 -
(?<!...)
负向反向断言(匹配前面不是某模式的内容)。// 匹配前面是 $ 的数字 const priceRegex = /(?<=\$)\d+/; console.log(priceRegex.exec('$100')[0]); // "100"
(3)dotAll
模式(s
标志)
-
让
.
匹配任意字符(包括换行符\n
)。const regex = /foo.bar/s; console.log(regex.test('foo\nbar')); // true(普通模式会返回 false)
(4)Unicode 属性转义(\p{...}
)
-
按 Unicode 属性匹配字符(如匹配所有字母、标点符号等)。
// 匹配所有字母 const regex = /\p{L}+/u; console.log(regex.test('你好Hello')); // true
五、 JSON.stringify
改进
-
修复了
JSON.stringify
对 Unicode 代理对(如 emoji)的处理问题。// 早期版本会返回损坏的 Unicode console.log(JSON.stringify('\uD83D\uDE00')); // ✅ 现在正确输出 ""😀""
六、模板字符串修正(修订规范)
-
明确模板字符串中非法转义序列的处理(如
\unicode
会报错)。// 早期允许,ES2018 明确报错 console.log(`\unicode`); // SyntaxError
注:如有缺失,请联系作者或在下方评论,我尽量在第一时间补充上去!!!