首頁 > web前端 > js教程 > 主體

使用陣列和函數在 JavaScript 中建立初學者友好的購物車的逐步指南

Susan Sarandon
發布: 2024-10-06 08:16:02
原創
406 人瀏覽過

Step-by-Step Guide to Building a Beginner-Friendly Shopping Cart in JavaScript Using Arrays and Functions

學習新程式語言的最佳方法是創建盡可能多的項目。如果您建立專注於您所學的迷你項目,您將獲得更順暢的初學者體驗。
我們的目標是避免「教學地獄」(即您不斷觀看多個教學影片而沒有任何具體項目來展示您的技能的可怕地方),並建立處理大型專案所需的信心。
在本文中,我將向初學者解釋如何使用基本的 Javascript 概念來建立購物車系統。

先決條件

要嘗試這個項目,您需要深入了解:

  • 功能
  • 方法
  • 數組

構建什麼?

購物車將有一個系統,使用者可以:

  • 將商品加入購物車
  • 從購物車移除商品
  • 查看購物車內容
  • 計算購物車中商品的總價

第 1 步:設定數據

首先,我們需要建立一些陣列來保存項目的資料。具體需要的陣列是:

  • itemNames:指定每個項目的名稱。
  • itemPrices:包含每件商品的價格。
  • itemQuantities:告訴特定商品有多少可用。
  • itemInStock:透過使用 true 或 false 來確定商品是否有庫存。

const itemNames = ["Laptop", "Phone"];
const itemPrices = [1000, 500];
const itemQuantities = [1, 2];
const itemInStock = [true, true];


登入後複製

第 2 步:打造具有功能的購物車

我們將創建一個主要的購物車功能,其中包含購物車的邏輯。我們將使用閉包來確保購物車保持私密性,並且只有某些功能可以與其互動。


const ShoppingCart = () => {
  const cart = []; // The cart is a private array

  // Add an item to the cart
  const addItemToCart = (itemIndex) => {
    if (itemInStock[itemIndex]) {
      cart.push(itemIndex);
      console.log(`${itemNames[itemIndex]} added to the cart`);
    } else {
      console.log(`${itemNames[itemIndex]} is out of stock`);
    }
  };

  // Remove an item from the cart
  const removeItemFromCart = (itemIndex) => {
    const index = cart.indexOf(itemIndex);
    if (index > -1) {
      cart.splice(index, 1);
    }
  };

  // Get the names of items in the cart
  const getCartItems = () => {
    return cart.map(itemIndex => itemNames[itemIndex]);
  };

  // Calculate the total price of items in the cart
  const calculateTotal = () => {
    return cart.reduce((total, itemIndex) => {
      return total + itemPrices[itemIndex] * itemQuantities[itemIndex];
    }, 0);
  };

  return {
    addItemToCart,
    removeItemFromCart,
    getCartItems,
    calculateTotal
  };
};


登入後複製

分解代碼:

  • addItemToCart(itemIndex):根據商品索引將商品加入購物車(僅當有庫存時)。
  • removeItemFromCart(itemIndex):使用索引從購物車中移除項目。
  • getCartItems():使用 map() 將索引轉換為名稱,並傳回購物車中商品的名稱。
  • calculateTotal():透過使用reduce()方法將購物車中商品的價格和數量相乘來計算總價。

第 3 步:測試購物車

完成的項目應該進行測試以確保其按需要工作。我們將測試:

  • 新增項目

  • 查看購物車

  • 看總價


const myCart = ShoppingCart();

// Add a Laptop (item 0)
myCart.addItemToCart(0);

// Add a Phone (item 1)
myCart.addItemToCart(1);

// View cart contents
console.log(myCart.getCartItems()); // Output: ['Laptop', 'Phone']

// Calculate the total price
console.log(myCart.calculateTotal()); // Output: 2000


登入後複製

分解代碼:

  • 我們透過呼叫它來創建購物車的實例: const myCart = shoppingCart();.
  • 我們使用 itemNames 陣列中的索引將商品加入購物車: myCart.addItemToCart(0);對於筆記型電腦和 myCart.addItemTocart(1);對於電話。
  • 我們使用 getCartItems() 列印購物車中商品的名稱
  • 最後,我們使用calculateTotal()計算總價。

第 4 步:從購物車中刪除商品

一個好的購物車系統必須允許使用者從購物車中刪除商品。我們可以透過呼叫removeItemFromCart()來做到這一點。


myCart.removeItemFromCart(1); // Remove the Phone

// View the updated cart
console.log(myCart.getCartItems()); // Output: ['Laptop']

// Recalculate the total price
console.log(myCart.calculateTotal()); // Output: 1000



登入後複製

獎勵:了解購物車系統中的閉包

閉包幫助購物車陣列保持私有,只能透過 ShoppingCart() 函數傳回的函數存取。

  • cart 陣列是在 shopping cart() 內部定義的,不能從外部直接存取。但是,由於 addItemTocart()、removeItemFromCart()、getCartItems() 和calculateTotal() 函數定義在同一範圍內,因此它們可以與 cart 互動。
  • 閉包是 JavaScript 的強大功能,有助於維護程式碼中的資料隱私和結構。

結論

透過使用基本陣列和函數,您已經建立了一個功能齊全的購物車系統,可以新增、刪除和計算商品總數。這個專案最棒的部分是它使用閉包來封裝和管理狀態,而不需要複雜的物件或類別。

最終程式碼


const itemNames = ["Laptop", "Phone"];
const itemPrices = [1000, 500];
const itemQuantities = [1, 2];
const itemInStock = [true, true];

const ShoppingCart = () => {
  const cart = [];

  const addItemToCart = (itemIndex) => {
    if (itemInStock[itemIndex]) {
      cart.push(itemIndex);
      console.log(`${itemNames[itemIndex]} added to the cart`);
    } else {
      console.log(`${itemNames[itemIndex]} is out of stock`);
    }
  };

  const removeItemFromCart = (itemIndex) => {
    const index = cart.indexOf(itemIndex);
    if (index > -1) {
      cart.splice(index, 1);
    }
  };

  const getCartItems = () => {
    return cart.map(itemIndex => itemNames[itemIndex]);
  };

  const calculateTotal = () => {
    return cart.reduce((total, itemIndex) => {
      return total + itemPrices[itemIndex] * itemQuantities[itemIndex];
    }, 0);
  };

  return {
    addItemToCart,
    removeItemFromCart,
    getCartItems,
    calculateTotal
  };
};

const myCart = ShoppingCart();
myCart.addItemToCart(0);
myCart.addItemToCart(1);
console.log(myCart.getCartItems());
console.log(myCart.calculateTotal());
myCart.removeItemFromCart(1);
console.log(myCart.getCartItems());
console.log(myCart.calculateTotal());


登入後複製

我希望您喜歡學習,我很高興您能夠建立更多精彩的專案!

以上是使用陣列和函數在 JavaScript 中建立初學者友好的購物車的逐步指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!