我查看了所有与此主题相关的链接,发现这种情况发生的原因可能是我的变量不是一个数组。我不太确定该如何解决。以下是我的代码:
function addStudent() {
var newStudentInfo = {
'studentNumber': document.getElementById("addStudentStudentNumber").value,
'name': document.getElementById("addStudentName").value
}
var oldStudentInfo = [];
oldStudentInfo = JSON.parse(localStorage.getItem("students")) || [];
oldStudentInfo.push(newStudentInfo);
localStorage.setItem("students", JSON.stringify(oldStudentInfo));
}
当我查看Google Chrome中的错误时,它告诉我:
Paused on exception: 'TypeError: oldStudentInfo.push is not a function'.
我哪里出错了?非常感谢提供帮助!
JSON.parse(localStorage.getItem("students"))
,而且它不是一个数组,在使用之前发送一个console.log()
以便你可以看到它是什么。 - Santiago HernándezObject {studentNumber: "r2424", name: "4242"}
。 - name1234567oldStudentInfo
是一个带有push
方法的数组,但是您后来将其覆盖为一个对象,该对象没有push
方法。 - dsuckau