JavaScript ES6+ 新特性完全指南:2024 年必会语法
ES6(ECMAScript 2015)是 JavaScript 的重大更新。本文介绍 ES6+ 的核心新特性。
let 和 const
// let: 块级作用域变量
let count = 0;
count = 1; // 可以修改
// const: 常量
const PI = 3.14;
// PI = 3.15; // 报错
// const 对象可以修改属性
const user = { name: '张三' };
user.name = '李四'; // 可以
// user = {}; // 报错
解构赋值
// 数组解构
const [a, b, c] = [1, 2, 3];
const [first, ...rest] = [1, 2, 3, 4]; // first=1, rest=[2,3,4]
// 对象解构
const { name, age } = { name: '张三', age: 28 };
const { name: userName } = { name: '张三' }; // 重命名
const { score = 0 } = {}; // 默认值
展开运算符
// 数组展开
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}
// 函数参数
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
箭头函数
// 传统函数
function add(a, b) {
return a + b;
}
// 箭头函数
const add = (a, b) => a + b;
// 多行
const getUser = (id) => {
const user = findById(id);
return user;
};
模板字符串
const name = '张三';
const greeting = `你好,${name}!`;
// 多行
const html = `
<div>
<h1>${name}</h1>
</div>
`;
Promise
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('完成'), 1000);
});
promise
.then(result => console.log(result))
.catch(error => console.error(error));
async/await
async function fetchData() {
try {
const response = await fetch('/api/data');
const data = await response.json();
return data;
} catch (error) {
console.error(error);
}
}
类
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `你好,我是${this.name}`;
}
static create(name, age) {
return new Person(name, age);
}
}
class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
}
模块化
// 导出
export const name = '张三';
export default class User {}
// 导入
import User, { name } from './user';
import * as utils from './utils';
其他新特性
可选链
const city = user?.address?.city;
空值合并
const value = null ?? '默认值';
逻辑赋值
a ??= b; // a = a ?? b
a &&= b; // a = a && b
a ||= b; // a = a || b
总结
ES6+ 让 JavaScript 更加强大和易用。掌握这些新特性,可以写出更简洁、更现代的代码。