0

0

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

花韻仙語

花韻仙語

发布时间:2024-10-09 11:43:02

|

916人浏览过

|

来源于dev.to

转载

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

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

  • 购物车数组是在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());


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

相关标签:

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
c语言const用法
c语言const用法

const是关键字,可以用于声明常量、函数参数中的const修饰符、const修饰函数返回值、const修饰指针。详细介绍:1、声明常量,const关键字可用于声明常量,常量的值在程序运行期间不可修改,常量可以是基本数据类型,如整数、浮点数、字符等,也可是自定义的数据类型;2、函数参数中的const修饰符,const关键字可用于函数的参数中,表示该参数在函数内部不可修改等等。

530

2023.09.20

go语言闭包相关教程大全
go语言闭包相关教程大全

本专题整合了go语言闭包相关数据,阅读专题下面的文章了解更多相关内容。

137

2025.07.29

golang map内存释放
golang map内存释放

本专题整合了golang map内存相关教程,阅读专题下面的文章了解更多相关内容。

75

2025.09.05

golang map相关教程
golang map相关教程

本专题整合了golang map相关教程,阅读专题下面的文章了解更多详细内容。

36

2025.11.16

golang map原理
golang map原理

本专题整合了golang map相关内容,阅读专题下面的文章了解更多详细内容。

60

2025.11.17

java判断map相关教程
java判断map相关教程

本专题整合了java判断map相关教程,阅读专题下面的文章了解更多详细内容。

41

2025.11.27

俄罗斯Yandex引擎入口
俄罗斯Yandex引擎入口

2026年俄罗斯Yandex搜索引擎最新入口汇总,涵盖免登录、多语言支持、无广告视频播放及本地化服务等核心功能。阅读专题下面的文章了解更多详细内容。

24

2026.01.28

包子漫画在线官方入口大全
包子漫画在线官方入口大全

本合集汇总了包子漫画2026最新官方在线观看入口,涵盖备用域名、正版无广告链接及多端适配地址,助你畅享12700+高清漫画资源。阅读专题下面的文章了解更多详细内容。

7

2026.01.28

ao3中文版官网地址大全
ao3中文版官网地址大全

AO3最新中文版官网入口合集,汇总2026年主站及国内优化镜像链接,支持简体中文界面、无广告阅读与多设备同步。阅读专题下面的文章了解更多详细内容。

28

2026.01.28

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号