想知道如何在localStorage
中更新數組obj時,我的localStorage
在刷新後創建一個新數組,而不是更新或添加新的obj。如何在localStorage中更新數組obj如果item已經存在
localStorage的OBJ -
cart - [{"Product":"Coke","Price":"1.99","Quantity":"1x "}]
addToCart函數,其中我添加我推對象array[]
var itemStorage = [];
for (var key in drinkCounter) {
...
var cartObj = { Product: key, Price: drinkCounter[key].price, Quantity: drinkCounter[key].count + 'x ' }
itemStorage.push(cartObj);
localStorage.setItem('cart', JSON.stringify(itemStorage));
...
}
這裏有一個JSfiddle,所以一旦你加入一個項目,並刷新頁面並添加相同或新的項目它重新創建localStorage
,我怎麼可以更新它,而不是每次刷新頁面時重新創建一個新的項目?
編輯 - 如果添加相同的項目,應該更新{Quantity:}
按照下面的答案,我想更新現有項目的項目數量卻沒有奏效。任何建議?
cartItems.forEach(function (item, i) {
if (item.Product == key) {
item.Quantity = drinkCounter[key].count;
// item.Quantity += 1; // or no avail
index = i;
}
});
固定localStorage的數量計算
if (index !== -1) {
cartItems[index].Quantity = parseInt(cartItems[index].Quantity) + 1 + 'x';
} else {
var cartObj = { Product: key, Price: drinkCounter[key].price, Quantity: drinkCounter[key].count + 'x ' }
cartItems.push(cartObj);
}
**編輯 - ** 約總價快速的問題,能有人指出爲什麼當我添加一個項目totalPrice是0
當它應該是物品價格
'sessionStorage'將在頁面重新加載後被刪除!我認爲yu意味着使用'localStorage'! –
對不起,我在我的代碼中改變了它,忘記在這裏改變它。但是它應該是'localStorage'。但是問題也存在,使用'localStorage' – MrNew