当 JavaScript 数组返回为未定义时如何修复它?

How do I fix my JavaScript array when it comes back as undefined?

我是 JavaScript 的新手,无法弄清楚为什么我的数组返回时未定义。

这是我的 CodePen 示例:https://codepen.io/TiffSmith126/pen/dyJedWQ

我正在做一个结果性格测验,将答案存储在一个数组中,我正在使用一个函数来获取数组中最常选择的选项。但是,我没有收到未定义的结果。此时我的函数不起作用,因为我的数组返回为未定义。有谁知道如何解决这一问题?如有任何帮助,我们将不胜感激。

// QUESTIONS

const questions = [
  {
    question: "Question 1",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 2",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 3",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 4",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 5",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 6",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 7",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 8",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 9",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 10",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  }
];

let currentQuestion = 0;
let score = [];
let selectedAnswersData = [];
let scoringData = [];
const totalQuestions = questions.length;

const container = document.querySelector(".quiz-container");
const questionEl = document.querySelector(".question");
const option1 = document.querySelector(".option1");
const option2 = document.querySelector(".option2");
const option3 = document.querySelector(".option3");
const nextButton = document.querySelector(".next");
const previousButton = document.querySelector(".previous");
const restartButton = document.querySelector(".restart");
const result = document.querySelector(".result");

//Function to generate question
function generateQuestions(index) {
  //Select each question by passing it a particular index
  const question = questions[index];
  const option1Total = questions[index].answer1Total;
  const option2Total = questions[index].answer2Total;
  const option3Total = questions[index].answer3Total;
  //Populate html elements
  questionEl.innerHTML = `${index + 1}. ${question.question}`;
  option1.setAttribute("data-total", `${option1Total}`);
  option2.setAttribute("data-total", `${option2Total}`);
  option3.setAttribute("data-total", `${option3Total}`);
  option1.innerHTML = `${question.answer1}`;
  option2.innerHTML = `${question.answer2}`;
  option3.innerHTML = `${question.answer3}`;
}

function loadNextQuestion() {
  const selectedOption = document.querySelector('input[type="radio"]:checked');
  //Check if there is a radio input checked
  if (!selectedOption) {
    alert("Please select your answer!");
    return;
  }
  //Get value of selected radio
  const answerScore = Number(
    selectedOption.nextElementSibling.getAttribute("data-total")
  );

  scoringData.push(selectedOption);
  ////Add the answer score to the score array
  score.push(answerScore);

  selectedAnswersData.push();

  function getMostFrequent(scoringData) {
    if (scoringData.length == 0) return null;
    var modeMap = {};
    var maxEl = scoringData[0],
      maxCount = 1;
    for (var i = 0; i < scoringData.length; i++) {
      var el = score[i];
      if (modeMap[el] == null) modeMap[el] = 1;
      else modeMap[el]++;
      if (modeMap[el] > maxCount) {
        maxEl = el;
        maxCount = modeMap[el];
      }
    }
    return maxEl;
  }

  const finalScore = getMostFrequent();

  //Finally we incement the current question number ( to be used as the index for each array)
  currentQuestion++;

  //once finished clear checked
  selectedOption.checked = false;
  //If quiz is on the final question
  if (currentQuestion == totalQuestions - 1) {
    nextButton.textContent = "Finish";
  }
  //If the quiz is finished then we hide the questions container and show the results
  if (currentQuestion == totalQuestions) {
    container.style.display = "none";
    result.innerHTML = `<h1 class="final-score">Your score: ${finalScore}</h1>
         <div class="summary">
            <h1>Summary</h1>
            <p>Possible - Personality Traits, see below for a summary based on your results:</p>
            <p>15 - 21- You Need Help</p>
            <p>10 - 15 - Good Soul</p>
            <p>5 - 10 - Meh </p>
            <p>5 - Are You Even Real</p>
        </div>
        <button class="restart">Restart Quiz</button>
         `;
    return;
  }
  generateQuestions(currentQuestion);
}

//Function to load previous question
function loadPreviousQuestion() {
  //Decrement quentions index
  currentQuestion--;
  //remove last array value;
  score.pop();
  //Generate the question
  generateQuestions(currentQuestion);
}

//Fuction to reset and restart the quiz;
function restartQuiz(e) {
  if (e.target.matches("button")) {
    //reset array index and score
    currentQuestion = 0;
    score = [];
    //Reload quiz to the start
    location.reload();
  }
}

generateQuestions(currentQuestion);
nextButton.addEventListener("click", loadNextQuestion);
previousButton.addEventListener("click", loadPreviousQuestion);
result.addEventListener("click", restartQuiz);
html {
  box-sizing: border-box;
}
*,
*:before,
*:after {
  box-sizing: inherit;
}
body {
  margin: 0;
  padding: 0;
  font-family: "Roboto", sans-serif;
  font-weight: 100;
  line-height: 1.7rem;
  background: #000;
}
.quiz-container {
  box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.2);
  text-shadow: 1px 1px white;
  padding: 3rem;
  text-shadow: 0 1px #00000010;
  width: 60%;
  margin: 5rem auto;
  display: flex;
  flex-direction: column;
  background: #000;
  min-height: 100vh;
}
.title {
  margin-top: 0;
  margin-bottom: 3rem;
  color: #f90;
  font-weight: 400;
  font-size: 2.5rem;
  text-align: center;
  text-transform: uppercase;
}
.question {
  margin: 2rem 0;
  font-size: 1.5rem;
  color: #fff;
}
.option {
  padding: 1rem;
  color: #fff;
  background: #f90;
  width: 80%;
  border-radius: 5px;
  transition: all 0.3s;
  margin-bottom: 15px;
}
.option:hover {
  background: #B36B00;
}
.option input:checked .option {
  background: #08038c;
  color: #000;
}
.controls > * {
  margin: 1rem;
}
button {
  padding: 0.5rem 1.5rem;
  border: none;
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1);
  border-radius: 5px;
  font-weight: 300;
  color: white;
  outline: none;
  transform: scale(0.98);
  transition: all 0.2s;
}
button.previous {
  background: #c84630;
}
button.next {
  background: #3c91e6;
}
button.restart {
  background: #0cf574;
  color: #fff;
  font-size: 2rem;
  margin-bottom: 1rem;
  transition: all 0.4s;
}
button.restart:hover {
  color: #fff;
}
button:hover,
button:focus {
  transform: scale(1);
  font-weight: 500;
  box-shadow: 1px 1px 1px rgba(255, 255, 255, 0.5);
}
.result {
  display: flex;
  flex-direction: column;
  padding: 2rem;
  justify-content: center;
  align-items: center;
  text-align: center;
  font-size: 2.5rem;
  min-height: 100vh;
}
.final-score {
  color: #f90;
}
.summary {
  font-size: 1rem;
  text-shadow: 1px 1px #ffffff50;
  color: #f90;
  background: #000;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding: 0 2rem;
  margin-bottom: 2rem;
}
.summary h1 {
  align-self: center;
}
<head>
    <title>Personality Quiz</title>
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
</head>

<body>

    <div class="quiz-container">
        <div class="title">Personality Quiz</div>
        <div id="question" class="question"></div>
        <label class="option">
            <input type="radio" name="option" value="1" />
            <span class="option1"></span>
        </label>
        <label class="option">
            <input type="radio" name="option" value="2" />
            <span class="option2"></span>
        </label>
        <label class="option">
            <input type="radio" name="option" value="3" />
            <span class="option3"></span>
        </label>
        <!-- Buttons -->
        <div class="controls">
            <button class="previous">Previous</button>
            <button class="next">Next</button>
        </div>
    </div>

    <div class="result">

    </div>
</body>

你正在执行一个函数,但没有在这一行中将参数传递给它

 const finalScore = getMostFrequent();

改为

 const finalScore = getMostFrequent(scoringData);

您忘记将 scoringData 添加到 const finalScore = getMostFrequent();

// QUESTIONS

const questions = [
  {
    question: "Question 1",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 2",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 3",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 4",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 5",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 6",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 7",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 8",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 9",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 10",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  }
];

let currentQuestion = 0;
let score = [];
let selectedAnswersData = [];
let scoringData = [];
const totalQuestions = questions.length;

const container = document.querySelector(".quiz-container");
const questionEl = document.querySelector(".question");
const option1 = document.querySelector(".option1");
const option2 = document.querySelector(".option2");
const option3 = document.querySelector(".option3");
const nextButton = document.querySelector(".next");
const previousButton = document.querySelector(".previous");
const restartButton = document.querySelector(".restart");
const result = document.querySelector(".result");

//Function to generate question
function generateQuestions(index) {
  //Select each question by passing it a particular index
  const question = questions[index];
  const option1Total = questions[index].answer1Total;
  const option2Total = questions[index].answer2Total;
  const option3Total = questions[index].answer3Total;
  //Populate html elements
  questionEl.innerHTML = `${index + 1}. ${question.question}`;
  option1.setAttribute("data-total", `${option1Total}`);
  option2.setAttribute("data-total", `${option2Total}`);
  option3.setAttribute("data-total", `${option3Total}`);
  option1.innerHTML = `${question.answer1}`;
  option2.innerHTML = `${question.answer2}`;
  option3.innerHTML = `${question.answer3}`;
}

function loadNextQuestion() {
  const selectedOption = document.querySelector('input[type="radio"]:checked');
  //Check if there is a radio input checked
  if (!selectedOption) {
    alert("Please select your answer!");
    return;
  }
  //Get value of selected radio
  const answerScore = Number(
    selectedOption.nextElementSibling.getAttribute("data-total")
  );

  scoringData.push(selectedOption);
  ////Add the answer score to the score array
  score.push(answerScore);

  selectedAnswersData.push();

  function getMostFrequent(scoringData) {
    if (scoringData.length == 0) return null;
    var modeMap = {};
    var maxEl = scoringData[0],
      maxCount = 1;
    for (var i = 0; i < scoringData.length; i++) {
      var el = score[i];
      if (modeMap[el] == null) modeMap[el] = 1;
      else modeMap[el]++;
      if (modeMap[el] > maxCount) {
        maxEl = el;
        maxCount = modeMap[el];
      }
    }
    return maxEl;
  }

  const finalScore = getMostFrequent(scoringData);

  //Finally we incement the current question number ( to be used as the index for each array)
  currentQuestion++;

  //once finished clear checked
  selectedOption.checked = false;
  //If quiz is on the final question
  if (currentQuestion == totalQuestions - 1) {
    nextButton.textContent = "Finish";
  }
  //If the quiz is finished then we hide the questions container and show the results
  if (currentQuestion == totalQuestions) {
    container.style.display = "none";
    result.innerHTML = `<h1 class="final-score">Your score: ${finalScore}</h1>
         <div class="summary">
            <h1>Summary</h1>
            <p>Possible - Personality Traits, see below for a summary based on your results:</p>
            <p>15 - 21- You Need Help</p>
            <p>10 - 15 - Good Soul</p>
            <p>5 - 10 - Meh </p>
            <p>5 - Are You Even Real</p>
        </div>
        <button class="restart">Restart Quiz</button>
         `;
    return;
  }
  generateQuestions(currentQuestion);
}

//Function to load previous question
function loadPreviousQuestion() {
  //Decrement quentions index
  currentQuestion--;
  //remove last array value;
  score.pop();
  //Generate the question
  generateQuestions(currentQuestion);
}

//Fuction to reset and restart the quiz;
function restartQuiz(e) {
  if (e.target.matches("button")) {
    //reset array index and score
    currentQuestion = 0;
    score = [];
    //Reload quiz to the start
    location.reload();
  }
}

generateQuestions(currentQuestion);
nextButton.addEventListener("click", loadNextQuestion);
previousButton.addEventListener("click", loadPreviousQuestion);
result.addEventListener("click", restartQuiz);
html {
  box-sizing: border-box;
}
*,
*:before,
*:after {
  box-sizing: inherit;
}
body {
  margin: 0;
  padding: 0;
  font-family: "Roboto", sans-serif;
  font-weight: 100;
  line-height: 1.7rem;
  background: #000;
}
.quiz-container {
  box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.2);
  text-shadow: 1px 1px white;
  padding: 3rem;
  text-shadow: 0 1px #00000010;
  width: 60%;
  margin: 5rem auto;
  display: flex;
  flex-direction: column;
  background: #000;
  min-height: 100vh;
}
.title {
  margin-top: 0;
  margin-bottom: 3rem;
  color: #f90;
  font-weight: 400;
  font-size: 2.5rem;
  text-align: center;
  text-transform: uppercase;
}
.question {
  margin: 2rem 0;
  font-size: 1.5rem;
  color: #fff;
}
.option {
  padding: 1rem;
  color: #fff;
  background: #f90;
  width: 80%;
  border-radius: 5px;
  transition: all 0.3s;
  margin-bottom: 15px;
}
.option:hover {
  background: #B36B00;
}
.option input:checked .option {
  background: #08038c;
  color: #000;
}
.controls > * {
  margin: 1rem;
}
button {
  padding: 0.5rem 1.5rem;
  border: none;
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1);
  border-radius: 5px;
  font-weight: 300;
  color: white;
  outline: none;
  transform: scale(0.98);
  transition: all 0.2s;
}
button.previous {
  background: #c84630;
}
button.next {
  background: #3c91e6;
}
button.restart {
  background: #0cf574;
  color: #fff;
  font-size: 2rem;
  margin-bottom: 1rem;
  transition: all 0.4s;
}
button.restart:hover {
  color: #fff;
}
button:hover,
button:focus {
  transform: scale(1);
  font-weight: 500;
  box-shadow: 1px 1px 1px rgba(255, 255, 255, 0.5);
}
.result {
  display: flex;
  flex-direction: column;
  padding: 2rem;
  justify-content: center;
  align-items: center;
  text-align: center;
  font-size: 2.5rem;
  min-height: 100vh;
}
.final-score {
  color: #f90;
}
.summary {
  font-size: 1rem;
  text-shadow: 1px 1px #ffffff50;
  color: #f90;
  background: #000;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding: 0 2rem;
  margin-bottom: 2rem;
}
.summary h1 {
  align-self: center;
}
<head>
    <title>Personality Quiz</title>
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
</head>

<body>

    <div class="quiz-container">
        <div class="title">Personality Quiz</div>
        <div id="question" class="question"></div>
        <label class="option">
            <input type="radio" name="option" value="1" />
            <span class="option1"></span>
        </label>
        <label class="option">
            <input type="radio" name="option" value="2" />
            <span class="option2"></span>
        </label>
        <label class="option">
            <input type="radio" name="option" value="3" />
            <span class="option3"></span>
        </label>
        <!-- Buttons -->
        <div class="controls">
            <button class="previous">Previous</button>
            <button class="next">Next</button>
        </div>
    </div>

    <div class="result">

    </div>
</body>