gpt4 book ai didi

javascript - 如何从localStorage中清除相同的对象并增加数量?

转载 作者:行者123 更新时间:2023-11-28 10:50:54 24 4
gpt4 key购买 nike

我正在创建一个客户端购物车。添加的产品保存在本地存储中,但是如果已经添加到本地存储中,如何增加产品数量呢?我有将产品添加到本地商店的功能,在这个功能中我增加了数量,但产品变得重复。

Product.prototype.addObjToLocalStore = function() {
var obj = {
'name': this.name,
'qty': this.qty,
'price': this.price,
'total': this.getPrice()
}
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];

for (k in oldItems) {
if(oldItems[k].name == obj.name) {
oldItems[k].qty += parseInt(obj.qty);
localStorage.setItem('itemsArray', JSON.stringify(oldItems[k].qty));
}
}

oldItems.push(obj);
localStorage.setItem('itemsArray', JSON.stringify(oldItems));
}

最佳答案

好吧,无论您是否找到该项目,您都可以 oldItems.push(obj) 到它,从而复制该项目。

所以在这种情况下我要做的不是使用数组,而是使用对象。对象的键是项目的标识符(在您的例子中是名称),值是项目的属性(数量、价格等)。就像这样:

Product.prototype.addObjToLocalStore = function() {
// oldItems is an object, not an array
var oldItems = JSON.parse(localStorage.getItem('itemsObject')) || {};
// If it exists, grab its quantity. If not, 0.
var oldQuantity = (oldItems[this.name] && oldItems[this.name].qty) || 0;
var obj = {
'name': this.name,
'qty': oldQuantity + this.qty,
'price': this.price,
'total': this.getPrice()
}

// Replace the old entry with the new.
// If doesn't exist, will be created.
oldItems[this.name] = obj;

// We're done here. Store the new object.
logalStorage.setItem('itemsObject', JSON.stringify(oldItems));
};

关于javascript - 如何从localStorage中清除相同的对象并增加数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33630617/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com