JavaScript:使用减号按钮从购物车中删除产品

kgqe7b3p  于 2023-03-11  发布在  Java
关注(0)|答案(2)|浏览(147)

我想在数量达到1件时,用“-”键清除加入购物车的产品,希望有人能帮我,我已经找了两天的解决方案了,先谢谢了。

//changeNumber

function changeNumber(action, id){

cart = cart.map((item)=> {

let = oldNumber = item.numberOfUnits;

if(item.id === id){

  if (action === "meno" && item.numberOfUnits >1) {
 oldNumber--
  } else if (action === "piu") {
    oldNumber++
     } 

     if (action === "meno" && item.numberOfUnits === 1){

       console.log("delete")
      console.log(cart.splice(item.id, 1));      
      }

updateCart();

}

return {
  ...item,
  numberOfUnits: oldNumber,
 
}

});

updateCart();
}
pobjuy32

pobjuy321#

map函数不允许在循环时删除元素。
有两种方法:
1.保存要删除内容的索引,然后在.map()之后调用delete cart[index]
1.使用其他技术更新购物车列表**(推荐)**

技术#1

function changeNumber(action, id) {
    var toRemove = null;
    var index = 0;

    [...]

    // Instead of the two console.logs
    toRemove = index;

    [...]

    // At the end of the map lambda
    index++;

    [...]

    // At the end of the changeNumber function
    if (toRemove !== null)
        delete cart[toRemove];
}

技巧2

使用对象{id: item}代替数组,这样就可以访问和修改特定的元素,而不必遍历所有元素。

var cart = {};

function addToCart(item) {
    if (item.id in cart) // Check if the item is already in the cart
        cart[item.id].numberOfUnits++;
    else {
        cart[item.id] = item; // You may want to copy the item instead of directly adding it
        item.numberOfUnits = 1; // May be unnecessary or unwanted, depending on your system
    }
}

function removeFromCart(item) {
    if (!(item.id in cart)) // If the item is already not in the cart
        return false; // The removal was already done
    cart[item.id].numberOfUnits--;
    if (cart[item.id].numberOfUnits <= 0) // The less-than is unnecessary, but a good check anyway
        delete cart[item.id];
    return true; // The removal was successful
}

// Example
addToCart({id: 5});
addToCart({id: 5});
addToCart({id: 7});

console.log(removeFromCart({id: 5})); // True; there was an item to remove
console.log(removeFromCart({id: 7})); // True; there was an item to remove
console.log(removeFromCart({id: 7})); // False; there was no item

console.log(cart);
lf5gs5x2

lf5gs5x22#

文档.getElementById(“电话-减号”).addEventListener(“单击”,函数(){

console.log('minus done');

        const phoneMinusVal=document.getElementById('case-number');
        const phNum=phoneMinusVal.value;

        if(phNum>0)
        phoneMinusVal.value=parseInt(phNum)-1;
        
    })

相关问题