[英]Why this code gives me "Uncaught TypeError: Cannot read properties of null (reading 'push')" error?
In this code I am getting error as Uncaught TypeError: Cannot read properties of null (reading 'push')在这段代码中,我收到错误,因为 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);
});
checkout this I hope it will fix your problem结帐这个我希望它会解决你的问题
let addbtn = document.getElementById("addbtn");
console.log('addbtn ', addbtn);
addbtn?.addEventListener("click", function (e) {
let addtxt = document.getElementById("addtxt");
let notes = localStorage.getItem("notes");
notesObj = JSON.parse(notes ?? '[]');
console.log('addtxt.value ', addtxt?.value);
notesObj.push(addtxt.value);
//getting error at this point. Don't know why
localStorage.setItem("notes", JSON.stringify(notesObj));
addtxt = "";
console.log(notesObj);
});
The issue is that you have the string 'null'
in your local storage.问题是您的本地存储中有字符串'null'
。
Yes you compare with null
, but notes
is still JSON at this point, and apparently it can be null
encoded as JSON.是的,您与null
进行了比较,但此时notes
仍然是 JSON,显然它可以将null
编码为 JSON。 So you'd also need to check for 'null'
as string.所以你还需要检查'null'
作为字符串。
Or, easier: Replace the whole if
with something like this:或者,更简单:用这样的东西替换整个if
:
const notesObj = (notes && JSON.parse(notes)) ?? []
If you want to be also resilient against invalid JSON in local storage, you can use this:如果您还想对本地存储中的无效 JSON 具有弹性,您可以使用:
let notesObj
try {
notesObj = JSON.stringify(notes) ?? []
} catch(e) {}
to fix this issue use localstorage.clear() in the console.要解决此问题,请在控制台中使用 localstorage.clear()。 that's it.就是这样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.