PHP前端开发

使用数组和函数在 JavaScript 中构建初学者友好的购物车的分步指南

百变鹏仔 4天前 #JavaScript
文章标签 数组

学习新编程语言的最佳方法是创建尽可能多的项目。如果您构建专注于您所学知识的迷你项目,您将获得更顺畅的初学者体验。
我们的目标是避免“教程地狱”(即您不断观看多个教程视频而没有任何具体项目来展示您的技能的可怕地方),并建立处理大型项目所需的信心。
在本文中,我将向初学者解释如何使用基本的 javascript 概念创建购物车系统。

先决条件

要尝试这个项目,您需要深入了解:

构建什么?

购物车将有一个系统,用户可以:

第 1 步:设置数据

首先,我们需要创建一些数组来保存项目的数据。具体需要的数组是:

const itemnames = ["laptop", "phone"];const itemprices = [1000, 500];const itemquantities = [1, 2];const iteminstock = [true, true];

第 2 步:使用功能构建购物车

我们将创建一个主要的购物车功能,其中包含购物车的逻辑。我们将使用闭包来确保购物车保持私密性,并且只有某些功能可以与其交互。

立即学习“Java免费学习笔记(深入)”;

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  };};

分解代码:

第 3 步:测试购物车

完成的项目应该进行测试以确保其按需要工作。我们将测试:

const mycart = shoppingcart();// add a laptop (item 0)mycart.additemtocart(0);// add a phone (item 1)mycart.additemtocart(1);// view cart contentsconsole.log(mycart.getcartitems()); // output: ['laptop', 'phone']// calculate the total priceconsole.log(mycart.calculatetotal()); // output: 2000

分解代码:

第 4 步:从购物车中删除商品

一个好的购物车系统必须允许用户从购物车中删除商品。我们可以通过调用removeitemfromcart()来做到这一点。

mycart.removeitemfromcart(1); // remove the phone// view the updated cartconsole.log(mycart.getcartitems()); // output: ['laptop']// recalculate the total priceconsole.log(mycart.calculatetotal()); // output: 1000

奖励:了解购物车系统中的闭包

闭包帮助购物车数组保持私有,只能通过 shoppingcart() 函数返回的函数访问。

结论

通过使用基本数组和函数,您已经构建了一个功能齐全的购物车系统,可以添加、删除和计算商品总数。这个项目最棒的部分是它使用闭包来封装和管理状态,而不需要复杂的对象或类。

最终代码

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());

我希望您喜欢学习,我很高兴您能够构建更多精彩的项目!