返回
ECMAScript 2016、2017 和 2018 中的新增功能及示例
前端
2023-10-03 23:53:42
很难跟踪 JavaScript (ECMAScript) 中的新功能,更难找到有用的代码示例。因此,在本文中,我将介绍在 ES2016、ES2017 和 ES2018(最终草案)中添加的 TC39 已完成提案中列出的所有 18 个功能,并向他们展示有用的示例。这是一个相当长的帖子,但应该是一个非常有用的资源。
为了使文章更具可读性,我将根据功能类型对其进行组织。
ES2016
- 箭头函数
const add = (a, b) => a + b;
- 扩展运算符
const numbers = [1, 2, 3, 4, 5];
const sum = [...numbers].reduce((a, b) => a + b);
- 对象展开运算符
const person = {
name: 'John',
age: 30
};
const newPerson = {
...person,
city: 'New York'
};
- 模板字符串
const name = 'John';
const age = 30;
const greeting = `Hello, my name is ${name} and I am ${age} years old.`;
ES2017
- Async/Await
async function fetchUserData() {
const response = await fetch('https://example.com/api/users');
const data = await response.json();
return data;
}
- 尾递归优化
function factorial(n) {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}
- 共享内存和原子操作
const sharedBuffer = new SharedArrayBuffer(1024);
const int32View = new Int32Array(sharedBuffer);
Atomics.add(int32View, 0, 1);
ES2018
- 正则表达式改进
const regex = /\u{1f600}/u;
- Async Iteration
async function* fetchUsernames() {
const response = await fetch('https://example.com/api/users');
const data = await response.json();
for (const user of data) {
yield user.username;
}
}
- 对象 Rest/Spread 属性
const person = {
name: 'John',
age: 30,
city: 'New York'
};
const { name, ...rest } = person;
- 可选链操作符
const user = {
name: 'John',
address: {
city: 'New York'
}
};
const city = user?.address?.city;
我希望本文对您有用。如果您有兴趣了解更多有关这些新功能的信息,我鼓励您查看 TC39 已完成提案列表。