ECMAScript 2018 (也称为 ES9) 是 ECMAScript 标准的最新版本。它于 2018 年 6 月发布,引入了一些新的特性和语法语言,并对一些已有的语言特性进行了改进。在本文中,我们将为您详细介绍 ES9 中的新特性及其用法示例,帮助您更好地了解和掌握这个新版本。
新特性一:Rest/Spread 属性
在 ES9 中,可以通过 Rest/Spread 属性来方便地操作对象和数组。
Rest 属性
Rest 属性可以将对象或数组中的其余部分组合成一个新的对象或数组。语法如下:
-- -------------------- ---- ------- -- --- ---- -- --- - -- -- ---- - - - -- -- -- -- -- -- -- - -- --------------- -- - --------------- -- - --------------- -- - -- -- -- - - -- --- ---- -- --- --- -- ----- - --- -- -- -- --- --------------- -- - --------------- -- - --------------- -- --- -- --展开代码
Spread 属性
Spread 属性则可以将对象或数组中的元素展开到另一个对象或数组中。语法如下:
-- -------------------- ---- ------- -- --- ------ -- --- ---- - - -- -- -- - -- --- ---- - - -------- -- - -- ------------------ -- - -- -- -- -- -- - - -- --- ------ -- --- ---- - --- -- --- --- ---- - --- -- --- --- ---- - --------- --------- ------------------ -- --- -- -- -- -- --展开代码
新特性二:Promise.prototype.finally()
Promise.prototype.finally()
方法在 Promise 执行完毕后,无论 Promise 是成功还是失败,都会执行一个指定的回调函数。
Promise.resolve(1) .then(result => result + 2) .finally(() => console.log("finally executed!")); // 输出:finally executed!
新特性三:正则表达式命名捕获组
在 ES9 中,正则表达式引入了一种新的语法来命名捕获组,使它们更直观易懂。
const RE_DATE = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/; const matchObj = RE_DATE.exec("2018-06-22"); console.log(matchObj.groups.year); // 2018 console.log(matchObj.groups.month); // 06 console.log(matchObj.groups.day); // 22
新特性四:异步迭代器
异步迭代器是一种用于异步遍历对象的方法,它使用 Symbol.asyncIterator
来代替 Symbol.iterator
。
async function asyncGenerator() { const list = [Promise.resolve(1), Promise.resolve(2), Promise.resolve(3)]; for await (const item of list) { console.log(item); } } // 输出:1, 2, 3
总结
ES9 的新特性为 JavaScript 开发者提供了更加便利和优雅的编程体验。Rest/Spread 属性、Promise.prototype.finally()、正则表达式命名捕获组和异步迭代器都是非常实用的语言特性,我们应当加以学习和使用。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/652263eb95b1f8cacd9d2f39