我一直在尝试更新我的本地存储,但是不知何故,而不是不断更新,该阵列一直在被替换。有人可以帮我吗?这是我的代码。
function saveRun(){
runName = prompt("Please give a name for this run","");
runInstance.setRunName(runName);
savedRuns.push(runInstance);
console.log("Run instance : " + runInstance);
if (typeof(Storage) !== "undefined")
{
//Stringify runInstance to a JSON string
if (typeof localStorage.getItem("savedRuns") !== null) {
//Retrieve the stored JSON string
let retrievedRun = localStorage.getItem(runKey);
//Parse into a new variable
let runObject = JSON.parse(retrievedRun);
//Convert object into a JSON string
let stringifiedRun = JSON.stringify(savedRuns);
//Store this JSON string to local storage using the runKey
localStorage.setItem(runKey,stringifiedRun);
//console.log("Saved runs: " + savedRuns)
} else {
//Convert object into a JSON string
let stringifiedRun = JSON.stringify(savedRuns);
//Store this JSON string to local storage using the runKey
localStorage.setItem(runKey,stringifiedRun);
}
}
else {
console.log("Error: localStorage is not supported by current browser.");
}
//Now clear memory.
runInstance = null;
}
答案 0 :(得分:0)
您的代码检索retrievedRun
并将其解析为runObject
,然后完全忽略它,而是继续对savedRuns
进行字符串化并保存。是的,它已完全替换。如果要更新,则需要修改runObject
,然后对其进行字符串化和保存,而不是完全保存其他内容(savedRuns
/ stringifiedRun
)。
另一个问题是,正如SomePerformance在评论中指出的那样,typeof localStorage.getItem("savedRuns") !== null
将始终为真。您要么要删除typeof
(localStorage.getItem("savedRuns") !== null
),要么将null
更改为"null"
(typeof localStorage.getItem("savedRuns") !== "null"
)。