我的项目需要这个解决方案。这对我来说非常重要。 我想用键和索引从本地存储更新对象值 为了 我的购物车应用程序。
(购物车中产品数量的减少按钮)
示例。
function decreaseQuantity(index) {
var oldQty = localStorage.cart[index].quantity;
var newQty = oldQty - 1;
localStorage.setItem(cart[index].quantity, newQty);
}
最佳答案
您不能在localStorage
中存储复杂的对象,您只能将数据存储为string
。
如果您想将购物车对象存储到 locaStorage
中,您需要使用 JSON.stringify
将其序列化为字符串并按如下方式存储。
window.localStorage.setItem('cart', JSON.stringify(cart));
注意:这里'cart'是关键。
要返回,更改它并存储回来,你需要像下面那样做。
var data = window.localStorage.getItem('cart');
if (data != null) {
let cart= JSON.parse(data);
cart[index].quantity = cart[index].quantity -1;
window.localStorage.setItem('cart', JSON.stringify(cart));
}
关于javascript - 如何从索引和键更新本地存储对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54966531/