javascript - 如何从索引和键更新本地存储对象值
问题描述
我的项目需要这个解决方案。它对我来说非常重要。我想从我的购物车应用程序的本地存储中使用键和索引更新对象值。
(购物车中产品数量的减少按钮)
示例。
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));
注意:这里的“购物车”是关键。
要返回、更改并存储回来,您需要执行以下操作。
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));
}
推荐阅读
- c# - Asp.Net MVC 分层架构中的循环依赖
- java - 弹簧控制器:接受许多不同格式的日期/时间
- java - 从 DatePickerFragment 获取标签时出错
- php - 学说做太多的查询
- python - 数独网格生成器不使列不同的数字
- python - 网页上未显示机器学习预测的结果
- python - 计算和映射字符串出现的次数
- java - 遍历Java中所有嵌套子对象时如何避免多个for循环?
- python - Python 金融知识词典
- postgresql - 在 typescript/javascript 中调用的查询在“timestamp $3”处返回语法错误,PSQL 中的相同查询运行没有问题