ES6(ES2015)带来了大量现代语法特性,如箭头函数、解构赋值、模板字符串等。这些新语法在格式化时有其特殊规则,掌握它们能让代码更加优雅。
箭头函数
基本格式化
// 单参数,可省略括号
const double = x => x * 2;
// 多参数
const add = (a, b) => a + b;
// 多行函数体
const process = (data) => {
const result = [];
for (const item of data) {
result.push(item * 2);
}
return result;
};
// 返回对象字面量需要括号
const getUser = () => ({
name: 'test',
age: 18
});
箭头函数 vs 普通函数
// 推荐:简短逻辑用箭头函数
const square = x => x * x;
const greet = name => `Hello, ${name}`;
// 推荐:复杂逻辑用普通函数
function processData(data) {
const filtered = data.filter(item => item.active);
const mapped = filtered.map(item => item.value);
return mapped.reduce((sum, val) => sum + val, 0);
}
解构赋值
对象解构
// 基本解构
const { name, age } = user;
// 重命名
const { name: userName, age: userAge } = user;
// 默认值
const { name = '匿名', age = 0 } = user;
// 嵌套解构
const { name, address: { city, street } } = user;
// 函数参数解构
function greet({ name, age }) {
return `${name}, ${age}岁`;
}
数组解构
// 基本解构
const [first, second] = array;
// 跳过元素
const [first, , third] = array;
// 剩余元素
const [first, ...rest] = array;
// 交换变量
[a, b] = [b, a];
// 函数返回值解构
function getPosition() {
return [100, 200];
}
const [x, y] = getPosition();
模板字符串
基本用法
// 多行字符串
const html = `
<div class="card">
<h2>${title}</h2>
<p>${content}</p>
</div>
`;
// 表达式
const message = `Hello, ${user.name}! You are ${user.age} years old.`;
// 函数调用
const result = `Total: ${calculateTotal(items)}`;
标签模板
// 标签函数
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
const value = values[i] ? `<mark>${values[i]}</mark>` : '';
return result + str + value;
}, '');
}
const name = 'World';
const output = highlight`Hello, ${name}!`;
// 输出:Hello, <mark>World</mark>!
类与继承
类的格式化
class User {
// 构造函数
constructor(name, age) {
this.name = name;
this.age = age;
}
// 实例方法
greet() {
return `Hi, I'm ${this.name}`;
}
// getter
get info() {
return `${this.name}, ${this.age}岁`;
}
// setter
set nickname(value) {
this._nickname = value;
}
// 静态方法
static create(data) {
return new User(data.name, data.age);
}
}
// 继承
class Admin extends User {
constructor(name, age, role) {
super(name, age);
this.role = role;
}
// 方法重写
greet() {
return `${super.greet()} (Admin)`;
}
}
Promise 与 async/await
Promise 链
// 推荐格式
fetchData()
.then(data => processData(data))
.then(result => displayResult(result))
.catch(error => handleError(error));
// 多行 then
fetchData()
.then(data => {
const processed = processData(data);
return processed;
})
.then(result => {
displayResult(result);
})
.catch(error => {
console.error('Error:', error);
handleError(error);
});
async/await
// 基本用法
async function loadUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
const user = await response.json();
return user;
} catch (error) {
console.error('Failed to load user:', error);
throw error;
}
}
// 并行执行
async function loadAll() {
const [users, posts, comments] = await Promise.all([
fetchUsers(),
fetchPosts(),
fetchComments()
]);
return { users, posts, comments };
}
模块导入导出
ES Module
// 命名导出
export const API_URL = 'https://api.example.com';
export function fetchData() { }
export class UserService { }
// 默认导出
export default class App { }
// 命名导入
import { API_URL, fetchData } from './api.js';
// 默认导入
import App from './App.js';
// 全部导入
import * as Utils from './utils.js';
// 重命名导入
import { fetchData as load } from './api.js';
格式化建议
// 导入顺序
// 1. 第三方库
import React from 'react';
import axios from 'axios';
// 2. 内部模块
import { API_URL } from '@/config';
import UserService from '@/services/UserService';
// 3. 相对路径
import { formatDate } from './utils';
import styles from './App.module.css';
展开运算符
// 数组展开
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
// 对象展开
const obj1 = { name: 'test' };
const obj2 = { ...obj1, age: 18 }; // { name: 'test', age: 18 }
// 函数参数
const values = [1, 2, 3];
Math.max(...values); // 3
// 合并对象
const merged = { ...defaults, ...options, ...overrides };
可选链与空值合并
// 可选链
const city = user?.address?.city;
const result = obj?.method?.();
// 空值合并
const name = user.name ?? '匿名';
const count = data.count ?? 0;
// 组合使用
const displayName = user?.profile?.name ?? '未知用户';
格式化建议总结
| 语法 | 建议 |
|---|---|
| 箭头函数 | 简短逻辑单行写,复杂逻辑多行写 |
| 解构赋值 | 每行一个解构项,保持对齐 |
| 模板字符串 | 超过 80 字符换行 |
| 类 | 方法之间空一行 |
| async/await | try/catch 包裹,错误处理清晰 |
| 导入 | 按来源分组,字母排序 |
总结
ES6+ 语法让 JavaScript 更加强大和优雅。掌握正确的格式化方式,能让现代 JS 代码既简洁又易读。