ES6+ 特性
现代 JavaScript(ES6 及更高版本)引入了许多强大的新特性。
解构赋值
javascript
// 数组解构
const [a, b, c] = [1, 2, 3];
// 对象解构
const { name, age } = { name: '张三', age: 25 };
// 默认值
const { x = 0, y = 0 } = {};
展开运算符
javascript
// 数组展开
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
// 对象展开
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }
Promise 和 async/await
javascript
// Promise
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
// async/await
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
模块化
javascript
// 导出
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
export default class Calculator {
// ...
}
// 导入
import Calculator, { PI, add } from './math.js';
类
javascript
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`你好,我是${this.name}`);
}
}
class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
study() {
console.log(`${this.name}正在学习`);
}
}
可选链和空值合并
javascript
// 可选链
const userName = user?.profile?.name;
// 空值合并
const displayName = userName ?? '访客';