猿问

更新数组中的对象并且它有效,但也添加了一个神秘的数组

我正在尝试在我正在制作的个人项目上创建添加到购物车功能。购物车本身是一个包含一系列产品和小计的对象。它看起来像这样:


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

我打算为此做的是:

  1. 从数组中取出现有产品并将其绑定到oldProduct

  2. 完全使用将现有产品从阵列中移除slice

  3. 通过将数量加 1map并将其绑定到来更新现有产品updatedProduct

  4. 将这个更新的产品推到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时说它是一个对象,所以我真的不知道发生了什么。任何帮助将不胜感激。


繁星点点滴滴
浏览 140回答 2
2回答

扬帆大鱼

我认为你想得太多了,你也在用filter你的意思find,slice当你的意思splice。不过不用担心。我想你想要这样的东西: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,};let productId = 3;cart.products.map(p => {  if (p.prodId === productId) {    p.quantity++;    cart.subTotal += p.price;  }});console.log(cart)基本上,如果我理解的话,您只想增加具有给定 ID 的产品的数量。我对其进行了进一步编辑并扩展了该功能,以将产品的价格也添加到小计中。没那么简单,但也许你需要/想要什么?

莫回无

在你的情况下,oldProduct.map(p => p.quantity++);返回一个包含新数量的数组,然后将其推入products数组。您想要获取具有更新数量的对象并将其推送。还,而不是使用.filterthen .indexOf,你可以使用.findIndex我相信,鉴于您要尝试做的事情,您正在寻找.splice而不是.slicelet 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 index = products.findIndex(p => p.prodId === productId); // findIndexif (index > -1) {  let oldProduct = products[index]  products.splice(index, 1); // .splice  oldProduct.quantity++;  products.push(oldProduct); // push the object}console.log(products);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答