
学习新编程语言的最佳方法是创建尽可能多的项目。如果您构建专注于您所学知识的迷你项目,您将获得更顺畅的初学者体验。
我们的目标是避免“教程地狱”(即您不断观看多个教程视频而没有任何具体项目来展示您的技能的可怕地方),并建立处理大型项目所需的信心。
在本文中,我将向初学者解释如何使用基本的 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 步:使用功能构建购物车
我们将创建一个主要的购物车功能,其中包含购物车的逻辑。我们将使用闭包来确保购物车保持私密性,并且只有某些功能可以与其交互。
立即学习“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 };};
分解代码:
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 contentsconsole.log(mycart.getcartitems()); // output: ['laptop', 'phone']// calculate the total priceconsole.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 cartconsole.log(mycart.getcartitems()); // output: ['laptop']// recalculate the total priceconsole.log(mycart.calculatetotal()); // output: 1000
奖励:了解购物车系统中的闭包
闭包帮助购物车数组保持私有,只能通过 shoppingcart() 函数返回的函数访问。
购物车数组是在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 中构建初学者友好的购物车的分步指南的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1493054.html
微信扫一扫
支付宝扫一扫