在這段代碼中,我收到錯誤,因為 Uncaught TypeError: Cannot read properties of null (reading 'push')
console.log("HI");
let addbtn = document.getElementById("addbtn");
addbtn.addEventListener("click", function (e) {
let addtxt = document.getElementById("addtxt");
let notes = localStorage.getItem("notes");
if (notes == null) {
notesObj = [];
} else {
notesObj = JSON.parse(notes);
}
notesObj.push(addtxt.value);
//getting error at this point. Don't know why
localStorage.setItem("notes", JSON.stringify(notesObj));
addtxt = "";
console.log(notesObj);
});
uj5u.com熱心網友回復:
結帳這個我希望它會解決你的問題
let addbtn = document.getElementById("addbtn");
addbtn.addEventListener("click", function (e) {
let addtxt = document.getElementById("addtxt");
let notes = localStorage.getItem("notes");
notesObj = JSON.parse(notes ?? '[]')
notesObj.push(addtxt.value);
//getting error at this point. Don't know why
localStorage.setItem("notes", JSON.stringify(notesObj));
addtxt = "";
console.log(notesObj);
});
uj5u.com熱心網友回復:
問題是'null'您的本地存盤中有字串。
是的,您與 進行了比較null,但此時notes仍然是 JSON,顯然它可以null編碼為 JSON。所以你還需要檢查'null'字串。
或者,更簡單:用這樣的if東西替換整個:
const notesObj = (notes && JSON.parse(notes)) ?? []
如果您還想對本地存盤中的無效 JSON 具有彈性,您可以使用:
let notesObj
try {
notesObj = JSON.stringify(notes) ?? []
} catch(e) {}
uj5u.com熱心網友回復:
要解決此問題,請在控制臺中使用 localstorage.clear()。就是這樣。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/311105.html
標籤:javascript
下一篇:如何在C#中撰寫帶有變數類的函式
