Home > Net >  console gives a string isn't a function error
console gives a string isn't a function error

Time:12-05

I'm creating a quiz and console shows a problem with split, that it's not a function, but it worked before. I've tried using toString method but it doesn't help, console says instead that can't read properties of null. If someone could help me, it would be appreciated.

let correctAnswer = document.getElementById("correct-answers");
    document.querySelector(".check").onclick = function () {
        /* Hide unneeded sections and showing scores */
        quiz.classList.add("hidden");
        correctAnswer.classList.remove("hidden");

        /*Showing all previous scores */
        const lastScore = localStorage.getItem("latestScore") || [];

        const scoreDetail = lastScore.split(',');

        scoreDetail.push(score);

        localStorage.setItem("latestScore", scoreDetail);

        let userScoreTemplate = `<h2>This Round's Score: ${score}</h2>`;

        scoreDetail.map((items, index) => {
            userScoreTemplate  = `<h3>Score ${index}: ${items}</h3>`
        });

        let userScoreBoard = document.getElementById("user-score");

        userScoreBoard.innerHTML = userScoreTemplate;

CodePudding user response:

localStorage.getItem() will return a string.

You need adjust your code accordingly to default to a string in case the item is not defined:

const lastScore = localStorage.getItem("latestScore") || "";

CodePudding user response:

In your code lastScore is an array, not a string, so the split method will not work on it. It works only on strings.You can use JSON.Parse like that. This will convert array data into javascript array.

     const scoreDetail = JSON.parse(lastScore) || [];

scoreDetail.push(score);

And after that convert the array into a JSON string :

      localStorage.setItem("latestScore", JSON.stringify(scoreDetail));

CodePudding user response:

is latest score is a obj/array/string or what? If it's an array/object then wrap localStorage.getItem in JSON.parse() so js can convert array data into js array

  • Related