Skip to content

Shopping Cart Logic

中等 约 35 分钟

你将构建什么

shopping cart 系统使用函数到 添加/移除项, calculate subtotal, apply 百分比 discounts, and compute 最终总计使用 tax.

学习目标

  • Manage 集合的 项对象 in 数组
  • Use 数组方法 (查找, 筛选, reduce) for calculations
  • Implement 数量 tracking and 项 removal
  • Apply discounts and tax 到 compute 最终 price

前置要求

  • 数组 and 数组方法 (推送, 查找, 筛选, reduce)
  • 对象使用属性 (name, price, 数量)
  • 函数使用参数 and 返回值

步骤

  1. 1

    创建 cart and addItem 函数

    开始使用空 cart 数组. addItem 函数 takes product 对象 and 数量. 如果 product 是 already in cart, increase 它的数量; 否则, 添加新 条目.

    代码
    let cart = [];
    
    function addItem(product, quantity = 1) {
      const existing = cart.find(item => item.id === product.id);
      if (existing) {
        existing.quantity += quantity;
      } else {
        cart.push({ ...product, quantity });
      }
      return cart;
    }

    预期结果

    添加相同 product 两次 increases 它的数量相反的 创建 duplicate.

  2. 2

    Implement removeItem

    编写函数到 移除项 通过 id, or reduce 它的数量如果数量是 specified. 如果数量 reaches 0, 移除项 完全.

    代码
    function removeItem(id, quantity = Infinity) {
      const item = cart.find(i => i.id === id);
      if (!item) return cart;
      item.quantity -= quantity;
      if (item.quantity <= 0) {
        cart = cart.filter(i => i.id !== id);
      }
      return cart;
    }

    预期结果

    removeItem('apple', 2) reduces apple's 数量通过 2; removeItem('apple') 移除它 完全.

  3. 3

    Calculate subtotal

    Use reduce 方法到 总和上 price * 数量 for 每个项 in cart. 这个 gives subtotal 之前 discounts and tax.

    代码
    function getSubtotal() {
      return cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
    }

    预期结果

    For 项使用 prices 10 and 20 (数量 2 每个), subtotal 是 60.

  4. 4

    Apply discount and tax

    编写 checkout 函数那个 takes discount 百分比 and tax 速率, 然后 computes 最终总计: subtotal → discount → tax.

    代码
    function checkout(discountPercent = 0, taxPercent = 0) {
      const subtotal = getSubtotal();
      const discount = subtotal * (discountPercent / 100);
      const afterDiscount = subtotal - discount;
      const tax = afterDiscount * (taxPercent / 100);
      const total = afterDiscount + tax;
      return { subtotal, discount, tax, total };
    }

    预期结果

    checkout(10, 8) on $100 subtotal gives discount $10, tax $7.20, 总计 $97.20.

  5. 5

    测试完整 flow

    添加几个 products, 移除 one, and 运行 checkout 使用 discount and tax 到 see 完整 breakdown.

    代码
    addItem({ id: 'apple', name: 'Apple', price: 1.50 }, 3);
    addItem({ id: 'bread', name: 'Bread', price: 3.00 }, 2);
    addItem({ id: 'milk', name: 'Milk', price: 2.50 }, 1);
    removeItem('apple', 1); // remove 1 apple
    console.log('Cart:', cart);
    console.log('Checkout:', checkout(10, 8));

    预期结果

    Cart shows 2 apples, 2 breads, 1 milk; checkout shows subtotal, discount, tax, and 总计.

自己动手试试

你学到了什么

你构建完整 cart 系统 using 数组方法 (查找, 筛选, reduce) and 对象 manipulation — 相同模式 used in 真实 e-commerce backends, 只是使用数据库相反的 in-memory 数组.

相关资源

相关课程

  • 数组

    数组方法查找, 筛选, and reduce drive cart logic.

  • 对象

    每个 cart 项是 对象使用 id, name, price, and 数量.

相关练习

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回主题