为什么我在控制台中收到getStoredQuests.push不是函数的错误消息Object.addQuestionOnLocalStorageclass Question{ constructor(id, questionText, options, correctAnswer) { this.id = id; this.questionText = questionText; this.options = options; this.correctAnswer = correctAnswer; }}let questionLocalStorage = { setQuestionCollection: (newQuestion) => { localStorage.setItem('questionCollection', JSON.stringify(newQuestion)); }, getQuestionCollection: () => { return JSON.parse(localStorage.getItem('questionCollection')); }, removeQuestionCollection: () => { localStorage.removeItem('questionCollection'); }}newQuestion = new Question(questionId, newQuestText.value, optionsArr, corrAnswer);getStoredQuests = questionLocalStorage.getQuestionCollection();getStoredQuests.push(newQuestion);questionLocalStorage.setQuestionCollection(getStoredQuests);
1 回答

侃侃无极
TA贡献2051条经验 获得超10个赞
错误是因为getStoredQuests
不是数组。您可能没有考虑过最初本地存储是否没有问题,然后localStorage.getItem('questionCollection')
将返回空字符串,或者可能是您questionCollection
在本地存储中有一些带有键的值,但格式不正确,无法解析为 JSON 数组对象。
对于第一种情况,解决方案是检查是否localStorage.getItem('questionCollection')
为空,然后从中返回空数组getQuestionCollection
,对于第二种情况,您需要正确格式化数组“(将数组序列化以使用 JSON.stringify 存储)”。
为了让你的问题正确理解,打开控制台看看是否有红线
添加回答
举报
0/150
提交
取消