返回
ES7~ES14,带你领略 JavaScript 进阶之路(二)
前端
2024-01-29 20:49:01
ES7
数组扩展运算符
数组扩展运算符(...)允许您将数组中的元素展开为单个元素。这在许多情况下非常有用,例如:
- 将两个数组合并为一个数组
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combinedArray = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]
- 将数组元素作为函数参数传递
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3, 4, 5); // 15
对象扩展运算符
对象扩展运算符(...)允许您将对象中的属性展开为单个属性。这在许多情况下非常有用,例如:
- 将两个对象合并为一个对象
const obj1 = { name: 'John', age: 30 };
const obj2 = { city: 'New York' };
const combinedObject = { ...obj1, ...obj2 }; // { name: 'John', age: 30, city: 'New York' }
- 将对象属性作为函数参数传递
function greet({ name, age }) {
console.log(`Hello, ${name}! You are ${age} years old.`);
}
greet({ name: 'John', age: 30 }); // Hello, John! You are 30 years old.
ES8
模板字面量
模板字面量(template literals)允许您使用模板字符串来创建字符串。模板字符串可以包含变量和表达式,并且可以跨多行。这使得创建复杂的字符串变得更加容易。
const name = 'John';
const age = 30;
const greeting = `Hello, ${name}! You are ${age} years old.`;
console.log(greeting); // Hello, John! You are 30 years old.
ES9
async/await
async/await 是 JavaScript 中用于处理异步操作的语法。它允许您使用同步的方式编写异步代码,从而使代码更加易于理解和维护。
async function fetchUserData() {
const response = await fetch('https://example.com/user-data');
const data = await response.json();
return data;
}
fetchUserData().then(data => {
console.log(data);
});
ES10
Promise.allSettled()
Promise.allSettled() 是一个新的 Promise API,它允许您等待所有 Promise 都完成,无论它们是成功还是失败。这在许多情况下非常有用,例如:
- 等待多个异步操作同时完成
const promises = [
fetch('https://example.com/user-data'),
fetch('https://example.com/product-data')
];
const results = await Promise.allSettled(promises);
console.log(results);
- 检查所有 Promise 是否成功
const promises = [
fetch('https://example.com/user-data'),
fetch('https://example.com/product-data')
];
const results = await Promise.allSettled(promises);
const allSucceeded = results.every(result => result.status === 'fulfilled');
console.log(allSucceeded); // true
ES11
BigInt
BigInt 是一个新的数据类型,它可以表示任意精度的整数。这在许多情况下非常有用,例如:
- 处理大数字
const bigNumber = 9007199254740991n;
console.log(bigNumber); // 9007199254740991
- 安全地进行数学运算
const a = 1n;
const b = 2n;
const c = a + b;
console.log(c); // 3n
ES12
Optional Chaining
可选链接(?.)运算符允许您访问嵌套对象的属性,即使该属性不存在也不会报错。这在许多情况下非常有用,例如:
- 访问嵌套对象的属性,而无需检查该属性是否存在
const user = {
name: 'John',
address: {
street: '123 Main Street',
city: 'New York'
}
};
const city = user?.address?.city;
console.log(city); // New York
- 防止出现 TypeError 错误
const user = {
name: 'John'
};
const city = user?.address?.city;
console.log(city); // undefined
ES13
Nullish Coalescing Operator
空值合并(??)运算符允许您在两个值之间进行选择,如果第一个值为 null 或 undefined,则返回第二个值。这在许多情况下非常有用,例如:
- 设置默认值
const name = user?.name ?? 'Guest';
console.log(name); // John
- 防止出现 TypeError 错误
const user = {
name: null
};
const name = user?.name ?? 'Guest';
console.log(name); // Guest
结论
ES7 至 ES14 的新特性使 JavaScript 变得更加强大和灵活。通过学习和掌握这些新特性,您将能够编写出更加简洁、高效和可读的代码。如果您是 JavaScript 开发人员,我强烈建议您花时间学习这些新特性。