簡體   English   中英

如何更新localStorage中的值JSON?

[英]How to update the value JSON in localStorage?

在 localStorage 中,鍵“counters”包含 JSON 和一個 object,其字段是計數器的名稱,值是計數器的數值。 incrementCounter function,計數器名稱 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. 從本地存儲中獲取計數器 object
  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));
}

例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM