如何更新localStorage中的值JSON



在localStorage中,键"counters"包含一个对象的JSON,该对象的字段是计数器的名称,值是计数器的数值。incrementCounter函数,计数器的名称counterName作为输入的第一个参数传递给该函数。如何将counterName计数器增加1并更新localStorage中的数据?

我的代码:

function incrementCounter(counterName){
let counters = JSON.parse(localStorage.counters);
let values = Object.entries(counters);
for(let [counterName, value] of values){
return (`${counterName}: ${value+1}`);
}
localStorage.setItem("counters", JSON.stringify(values);
}

我想你正在寻找这样的东西:

  1. 从本地存储中获取计数器对象
  2. 使用counterName更新counter属性
  3. 如果不存在,请将值设置为1
  4. 保存回本地存储

function incrementCounter(counterName){
const counters = JSON.parse(localStorage.getItem('counters') || '{}');
counters[counterName] = (counters[counterName] || 0) + 1;
localStorage.setItem('counters', JSON.stringify(counters));
}

示例。

最新更新