【问题标题】:Loop property of an object对象的循环属性
【发布时间】:2018-09-12 12:29:39
【问题描述】:

我在 localStorage 中存储了一个购物车。如果我点击一个新产品,我想将它添加到购物车中。如果我再次点击相同的产品,我想添加数量以避免重复输入。

我想遍历对象并检查对象的“id”属性是否与发送给函数的“Id”参数匹配。如果是这样,我想更新该对象的“数量”,否则创建一个新对象并添加到“购物车”。现在我正在循环检查每个属性是否与“Id”-param 匹配。

这是物体上的样子:

{id:Id, qty: Qty, price: Price}  

这是函数:

handleAdd =(Id, Qty, Price) =>{
        var newCart=[]
        var cart = JSON.parse(window.localStorage.getItem('Cart'))

    if(cart !== null){
    for(var x in cart)
    {
        if(x.id === Id){
            x.qty = Number(x.qty) + Number(Qty) 

        }
        else{
            var item = {id:Id, qty: Qty, price: Price}
            newCart.push(item)
        }
    }
    }else{
         newCart= {id:Id, qty: Qty, price: Price}
    }

    window.localStorage.setItem('Cart', JSON.stringify(newCart))
}

【问题讨论】:

    标签: javascript reactjs loops local-storage


    【解决方案1】:

    编辑:刚刚意识到如果购物车存在于存储中,我的示例代码没有添加该项目,但该项目不存在于购物车中

    您无需从现有的购物车中构建新的购物车,只需使用已在仓库中的购物车即可。像这样的:

    handleAdd = (Id, Qty, Price) => {
        let cart = JSON.parse(window.localStorage.getItem('Cart'));
        // Track if item is already present
        let itemPresent = false;
    
        if(cart !== null){
            for(let i=0; i< cart.length; i++)
            {
                if (cart[i].id === Id) {
                    cart[i].qty = Number(cart[i].qty) + Number(Qty);
                    itemPresent = true;
                    break;
                }
            }
            // If item wasn't present, add it to cart
            if (itemPresent === false) {
                cart.push({id:Id, qty: Qty, price: Price});
            }
        } else {
             cart = [{id:Id, qty: Qty, price: Price}];
        }
    
        window.localStorage.setItem('Cart', JSON.stringify(cart));
    }
    

    未来的问题包括您当前方法的行为存在什么问题、您收到的任何错误消息等。

    【讨论】:

      猜你喜欢
      • 2012-10-03
      • 1970-01-01
      • 1970-01-01
      • 2021-11-20
      • 2014-01-26
      • 2017-09-05
      • 2012-07-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多