Skip to content

十七、ES6 实战综合案例

本节将通过几个综合案例,展示 ES6 特性在实际开发中的应用。

列表筛选 + 渲染(数组方法 + 模板字符串)

需求分析

创建一个商品列表,支持按价格筛选和按名称排序功能。

实现代码

javascript
// 商品数据
const products = [
  { id: 1, name: 'iPhone 13', price: 5999, category: '手机' },
  { id: 2, name: 'MacBook Pro', price: 12999, category: '电脑' },
  { id: 3, name: 'AirPods Pro', price: 1999, category: '配件' },
  { id: 4, name: 'iPad Pro', price: 6799, category: '平板' },
  { id: 5, name: 'Apple Watch', price: 2999, category: '配件' }
];

// 筛选函数
function filterProducts(products, maxPrice) {
  return products.filter(product => product.price <= maxPrice);
}

// 排序函数
function sortProducts(products, sortBy) {
  return [...products].sort((a, b) => {
    if (sortBy === 'price') {
      return a.price - b.price;
    } else if (sortBy === 'name') {
      return a.name.localeCompare(b.name);
    }
    return 0;
  });
}

// 渲染函数
function renderProducts(products) {
  const productList = document.getElementById('product-list');
  productList.innerHTML = '';
  
  if (products.length === 0) {
    productList.innerHTML = '<p>没有符合条件的商品</p>';
    return;
  }
  
  products.forEach(product => {
    const productItem = document.createElement('div');
    productItem.className = 'product-item';
    productItem.innerHTML = `
      <h3>${product.name}</h3>
      <p>价格: ¥${product.price}</p>
      <p>分类: ${product.category}</p>
    `;
    productList.appendChild(productItem);
  });
}

// 初始化
function init() {
  // 初始渲染所有商品
  renderProducts(products);
  
  // 绑定筛选事件
  document.getElementById('filter-btn').addEventListener('click', () => {
    const maxPrice = parseInt(document.getElementById('max-price').value) || Infinity;
    const filtered = filterProducts(products, maxPrice);
    renderProducts(filtered);
  });
  
  // 绑定排序事件
  document.getElementById('sort-select').addEventListener('change', (e) => {
    const sortBy = e.target.value;
    const sorted = sortProducts(products, sortBy);
    renderProducts(sorted);
  });
}

// 页面加载完成后初始化
window.addEventListener('DOMContentLoaded', init);

HTML 结构

html
<!DOCTYPE html>
<html>
<head>
  <title>商品列表</title>
  <style>
    .product-item {
      border: 1px solid #ddd;
      padding: 10px;
      margin: 10px 0;
      border-radius: 5px;
    }
  </style>
</head>
<body>
  <h1>商品列表</h1>
  
  <div>
    <label for="max-price">最高价格:</label>
    <input type="number" id="max-price" placeholder="输入最高价格">
    <button id="filter-btn">筛选</button>
  </div>
  
  <div>
    <label for="sort-select">排序方式:</label>
    <select id="sort-select">
      <option value="name">按名称</option>
      <option value="price">按价格</option>
    </select>
  </div>
  
  <div id="product-list"></div>
  
  <script src="app.js"></script>
</body>
</html>

异步请求数据展示(Promise + async/await)

需求分析

从 API 获取用户数据并展示,支持加载状态和错误处理。

实现代码

javascript
// 模拟 API 请求
function fetchUsers() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const random = Math.random();
      if (random > 0.2) { // 80% 概率成功
        resolve([
          { id: 1, name: 'John', email: 'john@example.com' },
          { id: 2, name: 'Jane', email: 'jane@example.com' },
          { id: 3, name: 'Bob', email: 'bob@example.com' }
        ]);
      } else {
        reject('获取用户数据失败');
      }
    }, 1000);
  });
}

// 渲染用户列表
function renderUsers(users) {
  const userList = document.getElementById('user-list');
  userList.innerHTML = '';
  
  users.forEach(user => {
    const userItem = document.createElement('div');
    userItem.className = 'user-item';
    userItem.innerHTML = `
      <h3>${user.name}</h3>
      <p>邮箱: ${user.email}</p>
    `;
    userList.appendChild(userItem);
  });
}

// 显示加载状态
function showLoading() {
  const loading = document.getElementById('loading');
  const error = document.getElementById('error');
  loading.style.display = 'block';
  error.style.display = 'none';
}

// 隐藏加载状态
function hideLoading() {
  const loading = document.getElementById('loading');
  loading.style.display = 'none';
}

// 显示错误信息
function showError(message) {
  const error = document.getElementById('error');
  error.textContent = message;
  error.style.display = 'block';
}

// 获取用户数据
async function getUserData() {
  try {
    showLoading();
    const users = await fetchUsers();
    hideLoading();
    renderUsers(users);
  } catch (error) {
    hideLoading();
    showError(error);
  }
}

// 初始化
function init() {
  // 绑定按钮事件
  document.getElementById('fetch-btn').addEventListener('click', getUserData);
  
  // 初始加载
  getUserData();
}

// 页面加载完成后初始化
window.addEventListener('DOMContentLoaded', init);

HTML 结构

html
<!DOCTYPE html>
<html>
<head>
  <title>用户数据</title>
  <style>
    .user-item {
      border: 1px solid #ddd;
      padding: 10px;
      margin: 10px 0;
      border-radius: 5px;
    }
    #loading {
      display: none;
      color: #666;
    }
    #error {
      display: none;
      color: red;
    }
  </style>
</head>
<body>
  <h1>用户数据</h1>
  
  <button id="fetch-btn">获取用户数据</button>
  <div id="loading">加载中...</div>
  <div id="error"></div>
  
  <div id="user-list"></div>
  
  <script src="app.js"></script>
</body>
</html>

模块化拆分小项目(import/export)

目录结构

project/
├── index.html
├── app.js
├── utils/
│   ├── math.js
│   └── format.js
└── components/
    ├── UserList.js
    └── ProductList.js

实现代码

utils/math.js

javascript
export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}

export function multiply(a, b) {
  return a * b;
}

export function divide(a, b) {
  if (b === 0) {
    return 'Cannot divide by zero';
  }
  return a / b;
}

utils/format.js

javascript
export function formatCurrency(amount) {
  return `¥${amount.toFixed(2)}`;
}

export function formatDate(date) {
  return new Date(date).toLocaleDateString();
}

components/UserList.js

javascript
export class UserList {
  constructor(container) {
    this.container = container;
  }
  
  render(users) {
    this.container.innerHTML = '';
    
    users.forEach(user => {
      const userItem = document.createElement('div');
      userItem.className = 'user-item';
      userItem.innerHTML = `
        <h3>${user.name}</h3>
        <p>邮箱: ${user.email}</p>
      `;
      this.container.appendChild(userItem);
    });
  }
}

components/ProductList.js

javascript
import { formatCurrency } from '../utils/format.js';

export class ProductList {
  constructor(container) {
    this.container = container;
  }
  
  render(products) {
    this.container.innerHTML = '';
    
    products.forEach(product => {
      const productItem = document.createElement('div');
      productItem.className = 'product-item';
      productItem.innerHTML = `
        <h3>${product.name}</h3>
        <p>价格: ${formatCurrency(product.price)}</p>
        <p>分类: ${product.category}</p>
      `;
      this.container.appendChild(productItem);
    });
  }
}

app.js

javascript
import { add, multiply } from './utils/math.js';
import { formatCurrency, formatDate } from './utils/format.js';
import { UserList } from './components/UserList.js';
import { ProductList } from './components/ProductList.js';

// 测试数学工具
console.log('5 + 3 =', add(5, 3));
console.log('5 * 3 =', multiply(5, 3));

// 测试格式化工具
console.log('格式化货币:', formatCurrency(123.45));
console.log('格式化日期:', formatDate(new Date()));

// 初始化用户列表
const userList = new UserList(document.getElementById('user-list'));
const users = [
  { id: 1, name: 'John', email: 'john@example.com' },
  { id: 2, name: 'Jane', email: 'jane@example.com' }
];
userList.render(users);

// 初始化商品列表
const productList = new ProductList(document.getElementById('product-list'));
const products = [
  { id: 1, name: 'iPhone 13', price: 5999, category: '手机' },
  { id: 2, name: 'AirPods Pro', price: 1999, category: '配件' }
];
productList.render(products);

HTML 结构

html
<!DOCTYPE html>
<html>
<head>
  <title>模块化项目</title>
  <style>
    .user-item, .product-item {
      border: 1px solid #ddd;
      padding: 10px;
      margin: 10px 0;
      border-radius: 5px;
    }
  </style>
</head>
<body>
  <h1>模块化项目示例</h1>
  
  <h2>用户列表</h2>
  <div id="user-list"></div>
  
  <h2>商品列表</h2>
  <div id="product-list"></div>
  
  <script type="module" src="app.js"></script>
</body>
</html>

面向对象小案例(Class)

需求分析

创建一个简单的购物车系统,支持添加商品、删除商品、计算总价等功能。

实现代码

javascript
// 商品类
class Product {
  constructor(id, name, price, quantity = 1) {
    this.id = id;
    this.name = name;
    this.price = price;
    this.quantity = quantity;
  }
  
  getTotalPrice() {
    return this.price * this.quantity;
  }
}

// 购物车类
class ShoppingCart {
  constructor() {
    this.items = [];
  }
  
  // 添加商品
  addItem(product) {
    const existingItem = this.items.find(item => item.id === product.id);
    if (existingItem) {
      existingItem.quantity += product.quantity;
    } else {
      this.items.push(product);
    }
  }
  
  // 删除商品
  removeItem(productId) {
    this.items = this.items.filter(item => item.id !== productId);
  }
  
  // 更新商品数量
  updateQuantity(productId, quantity) {
    const item = this.items.find(item => item.id === productId);
    if (item) {
      item.quantity = quantity;
      if (item.quantity <= 0) {
        this.removeItem(productId);
      }
    }
  }
  
  // 计算总价
  getTotal() {
    return this.items.reduce((total, item) => total + item.getTotalPrice(), 0);
  }
  
  // 获取购物车商品数量
  getItemCount() {
    return this.items.reduce((count, item) => count + item.quantity, 0);
  }
  
  // 清空购物车
  clear() {
    this.items = [];
  }
  
  // 获取购物车内容
  getItems() {
    return [...this.items];
  }
}

// 测试购物车
function testShoppingCart() {
  const cart = new ShoppingCart();
  
  // 添加商品
  cart.addItem(new Product(1, 'iPhone 13', 5999));
  cart.addItem(new Product(2, 'AirPods Pro', 1999, 2));
  
  console.log('购物车商品:', cart.getItems());
  console.log('商品总数:', cart.getItemCount());
  console.log('总价:', cart.getTotal());
  
  // 更新商品数量
  cart.updateQuantity(1, 2);
  console.log('更新后购物车:', cart.getItems());
  console.log('更新后总价:', cart.getTotal());
  
  // 删除商品
  cart.removeItem(2);
  console.log('删除后购物车:', cart.getItems());
  console.log('删除后总价:', cart.getTotal());
  
  // 清空购物车
  cart.clear();
  console.log('清空后购物车:', cart.getItems());
  console.log('清空后总价:', cart.getTotal());
}

// 运行测试
testShoppingCart();

通过这些综合案例,你可以看到 ES6 特性在实际开发中的应用。这些特性不仅使代码更加简洁易读,而且提高了开发效率。

© 2026 编程马·菜鸟教程 版权所有