ECMAScript2018(ES9)新特性
# 概述
ECMAScript2018 于2018年6月正式发布, 本文会介绍ECMAScript2018(ES9),即ECMAScript的第9个版本的新特性。
以下摘自官网:ecma-262 (opens new window)
ECMAScript 2018 introduced support for asynchronous iteration via the async iterator protocol and async generators. It also included four new regular expression features: the dotAll flag, named capture groups, Unicode property escapes, and look-behind assertions. Lastly it included object rest and spread properties.
# ECMAScript2018(ES9)
ES9聚焦于异步编程、正则表达式和对象操作的标准化。新增的特性如下:
- 异步迭代
Async Iteration
Reset/Spread
操作符和对象构建- 正则表达式
RegExp
增强 promise.finally
- 模版字符串改进
- 其它改进
# 异步迭代(Async Iteration
)
通过async/await
与迭代器的集合,支持异步循环操作
- 异步迭代器协议:
Symbol.asyncIterator
允许对象定义异步迭代行为 for await ...of
循环:用于遍历异步可迭代对象(如异步生成器)
# 示例
async function* fetchPosts() {
const urls = ['/api/post1', '/api/post2'];
for (const url of urls) {
yield await fetch(url).then(res => res.json());
}
}
// 使用 for await...of 遍历
(async () => {
for await (const post of fetchPosts()) {
console.log(post.title);
}
})();
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 兼容性

# 对象展开与剩余属性(Object Rest /Spread Properties
)
- 展开语法:用于复制对象的所有可枚举属性(浅拷贝)
const obj = { a: 1, b: 2 };
const newObj = { ...obj, c: 3 }; // { a: 1, b: 2, c: 3 }
1
2
2
- 剩余属性:用于收集对象中未被解构的属性
const { a, ...rest } = { a: 1, b: 2, c: 3 };
console.log(rest); // { b: 2, c: 3 }
1
2
2
# 兼容性


# 正则表达式增强
- dotAll标志:使正则表达式的点号
.
可以匹配包括换行符\n
在内的所有字符
const str = 'Hello\nWorld';
/Hello.World/s.test(str); // true(未加 s 标志时为 false)
1
2
2
- 命名捕获组(Name Capture Groups):通过
(?<name>pattern)
语法为捕获组命名,便于引用
const re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const { groups: { year, month, day } } = re.exec('2023-01-01');
console.log(year, month, day); // 2023 01 01
1
2
3
2
3
- Unicode属性转义(Unicode Property Escapes):通过
\p{...}
语法匹配Unicode
字符属性
// 匹配所有 emoji
const emoji = '👋 Hello 😊';
emoji.match(/\p{Emoji}/gu); // ['👋', '😊']
1
2
3
2
3
- 后行断言(Look-behind Assertions):通过
(?<=pattern)
语法支持向前或向后断言匹配
// 匹配美元符号后的数字(后行断言)
/(?<=\$)\d+/.exec('Price: $99'); // ['99']
// 匹配数字前的美元符号(先行断言)
/\$\d+(?= tax)/.exec('$99 tax'); // ['$99']
1
2
3
4
5
2
3
4
5
# 兼容性




# promise.finally
promise.finally
:无论Promise
对象的状态如何,都会执行finally
指定的回调函数
new Promise((resolve, reject) => {
resolve();
}).finally(() => {
console.log('finally');
});
1
2
3
4
5
2
3
4
5
# 兼容性

# 模版字符串改进
未引入新语法,但是规范了模版字符串的转义处理,如\u
和\x
// 避免意外转义错误
const str = String.raw`\u{1F600}`; // 直接输出 "\u{1F600}" 而非 Unicode 字符
1
2
2
# 其他改进
JSON.string
增强:支持处理超出范围的Unicode
字符
JSON.stringify('😀'); // 正确输出 "\ud83d\ude00"
1
- 函数参数列表和调用中的尾逗号:允许在函数参数和调用中使用尾逗号,提升代码维护性
function sum(a, b,) { // 合法
return a + b;
}
1
2
3
2
3
编辑 (opens new window)
上次更新: 2025/07/31, 05:54:29