我正在尝试在我正在制作的个人项目上创建添加到购物车功能。购物车本身是一个包含一系列产品和小计的对象。它看起来像这样:
let cart = {
products: [
{ prodId: 1, quantity: 1, price: 6.99 },
{ prodId: 2, quantity: 2, price: 4.99 },
{ prodId: 3, quantity: 1, price: 15.99 },
],
subTotal: 32.96,
};
我现在只对产品感兴趣,所以我 products = cart.products这样做了,我只是在处理这个:
products = [
{ prodId: 1, quantity: 1, price: 6.99 },
{ prodId: 2, quantity: 2, price: 4.99 },
{ prodId: 3, quantity: 1, price: 15.99 }
];
我有逻辑来检查产品是否已经在购物车中,所以我正在努力在用户点击购物车中已有商品的“添加到购物车”时增加数量。其逻辑如下所示:
let productId = 3;
let oldProduct = products.filter(p => p.prodId === productId);
let index = products.indexOf(oldProduct);
if (index > -1) {
products.slice(index, 1);
}
const updatedProduct = oldProduct.map(p => p.quantity++);
products.push(updatedProduct);
我打算为此做的是:
从数组中取出现有产品并将其绑定到oldProduct
完全使用将现有产品从阵列中移除slice
通过将数量加 1map并将其绑定到来更新现有产品updatedProduct
将这个更新的产品推到products
这有效,但也添加了一个数组products。所以控制台中的输出如下所示:
[
{ prodId: 1, quantity: 1, price: 6.99 },
{ prodId: 2, quantity: 2, price: 4.99 },
{ prodId: 3, quantity: 2, price: 15.99 },
[ 1 ]
]
我知道数组是添加的数量。我可能应该提到,在浏览器中,每次您点击购物车中已存在的产品的按钮时,新数组都会添加产品,因此,如果您点击第 3 项的按钮 5 次,产品数组将如下所示:
[
{ prodId: 1, quantity: 1, price: 6.99 },
{ prodId: 2, quantity: 2, price: 4.99 },
{ prodId: 3, quantity: 6, price: 15.99 },
[ 1 ],
[ 2 ],
[ 3 ],
[ 4 ],
[ 5 ]
]
我觉得是有关系的updatedProduct,因为我登录的时候只是数组,但是如果只是数组,那么数量就上不去了,所以我真的很困惑。另外,当我检查typeOf它updatedProduct时说它是一个对象,所以我真的不知道发生了什么。任何帮助将不胜感激。
扬帆大鱼
莫回无
相关分类