gpt4 book ai didi

javascript - Chrome 上的 localStorage 在 getItem、setItem 之后重置

转载 作者:行者123 更新时间:2023-12-02 13:50:12 27 4
gpt4 key购买 nike

我正在尝试使用 jQuery 将数据保存在 localStorage 中。每次刷新 Chrome 浏览器时,我尝试保存的数据都会重置。首先,我通过 getItem 从字典中检索数据,然后使用 setItem 设置它。听起来很简单,但我无法保存它。任何帮助表示赞赏。谢谢

这是我的js:

moneylove = {"snacks":{"c":1,"m":1,"e":2},"food":{"c":2,"m":0,"e":1},"soap":{"c":2,"m":0,"e":0},"toys":{"c":2,"m":1,"e":2}} //dog state
for (state in moneylove["snacks"]){
stateadd = JSON.parse(localStorage.getItem(state))
stateadd += moneylove["snacks"][state]
localStorage.setItem(state,JSON.stringify(stateadd))
}
console.log(localStorage)

最佳答案

您替换是因为每个子对象具有相同的属性,因此无论如何它都会替换。改成这样。

var moneylove = {"snacks":{"c":1,"m":1,"e":2},"food":{"c":2,"m":0,"e":1},"soap":{"c":2,"m":0,"e":0},"toys":{"c":2,"m":1,"e":2}} //dog state
for (state in moneylove["snacks"]){
stateadd = JSON.parse(localStorage.getItem(state))
stateadd += moneylove["snacks"][state]
localStorage.setItem("snacks" + state,JSON.stringify(stateadd)) // Make key be unique.
}
console.log(localStorage)

编辑

完整的计算和存储方法如下例。这样就可以计算出moneylove中每个对象的状态。

var moneylove = {"snacks":{"c":1,"m":1,"e":2},"food":{"c":2,"m":0,"e":1},"soap":{"c":2,"m":0,"e":0},"toys":{"c":2,"m":1,"e":2}} //dog state

for(var itemKey in moneylove) {
var item = moneylove[itemKey];
for (var stateKey in item){
var storageKey = itemKey + "-" + stateKey;
var stateadd = JSON.parse(localStorage.getItem(storageKey) || '0')
stateadd += item[stateKey];
localStorage.setItem(storageKey, JSON.stringify(stateadd)) // Make key be unique.
}
}
console.log(localStorage)

关于javascript - Chrome 上的 localStorage 在 getItem、setItem 之后重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41051876/

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