为了账号安全,请及时绑定邮箱和手机立即绑定

为什么我在控制台中收到一条错误消息,指出 getStoredQuests.push

为什么我在控制台中收到一条错误消息,指出 getStoredQuests.push

慕雪6442864 2021-12-23 10:29:20
为什么我在控制台中收到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 存储)”。

为了让你的问题正确理解,打开控制台看看是否有红线


查看完整回答
反对 回复 2021-12-23
  • 1 回答
  • 0 关注
  • 121 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号