猿问

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

为什么我在控制台中收到getStoredQuests.push不是函数的错误消息Object.addQuestionOnLocalStorage


class 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);


慕雪6442864
浏览 122回答 1
1回答

侃侃无极

错误是因为getStoredQuests不是数组。您可能没有考虑过最初本地存储是否没有问题,然后localStorage.getItem('questionCollection')将返回空字符串,或者可能是您questionCollection在本地存储中有一些带有键的值,但格式不正确,无法解析为 JSON 数组对象。对于第一种情况,解决方案是检查是否localStorage.getItem('questionCollection')为空,然后从中返回空数组getQuestionCollection,对于第二种情况,您需要正确格式化数组“(将数组序列化以使用 JSON.stringify 存储)”。为了让你的问题正确理解,打开控制台看看是否有红线
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答