I'm creating a quiz and I use local storage to show the user their previous attempts. And I have a problem. When you take the quiz one time, at the end it shows "Score 0:" and then "Score 1: actual score". I'm not sure where that score 0 came from. If anyone could help me, it would be much appreciated.
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.querySelector(".user-score");
userScoreBoard.innerHTML = userScoreTemplate;
};
CodePudding user response:
${index}
will be equal to 0 initially as Arrays always begin at index 0.
The fix:
scoreDetail.map((items, index) => {
index ; //increase index by 1;
userScoreTemplate = `<h3>Score ${index}: ${items}</h3>`;
});
Explanation TL;DR: Most programming languages use a zero-based index as an Array is a pointer and the index relates to the pointer's memory location. So the first memory location would be 0, and the second slot would be 1.
CodePudding user response:
Nevermind, I just had to do this:
scoreDetail.map((items, index) => {
userScoreTemplate = `<h3>Score ${index}: ${items}</h3>`;
if (items==""){
userScoreTemplate="";
};
});