开发者问题收集

为什么此代码给出“Uncaught TypeError: Cannot read properties of null (reading 'push')”错误?

2021-10-13
3591

在此代码中,我收到错误 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);
});
3个回答

问题是您的本地存储中有字符串 'null'

是的,您将其与 null 进行比较,但此时 notes 仍然是 JSON,显然它可以 null 编码为 JSON。因此,您还需要检查 'null' 是否为字符串。

或者,更简单:将整个 if 替换为以下内容:

const notesObj = (notes && JSON.parse(notes)) ?? []

如果您还想抵御本地存储中的无效 JSON,可以使用以下内容:

let notesObj
try {
  notesObj = JSON.stringify(notes) ?? []
} catch(e) {}
CherryDT
2021-10-13

检查一下我希望它能解决你的问题

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);
});
md. motailab
2021-10-13

要修复此问题,请在控制台中使用 localstorage.clear()。就是这样。

DEBANJAN BHATTACHARJEE
2021-10-13