[英]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);
}
我猜你正在尋找這樣的東西:
.
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.