如何从迭代中返回变量

How to Return variables from an iteration

本文关键字:返回 变量 迭代      更新时间:2023-09-26

大家好,我正在创建这个javascript测试应用程序,我有一些错误,我不能弄清楚。

正确显示,但错误在输出中,应该返回"您回答了(回答的问题中没有回答的问题)of(总问题数)"。这里,当值为true时,它只显示0。

下面是我的脚本。由于

var pos = 0,
  test, test_status, question, choice, choices, chA, chB, chC, correct = 0;
var questions = [
  ["What is 10 + 4?", "12", "14", "16", "B"],
  ["What is 10 + 5?", "15", "14", "16", "A"],
  ["What is 20 + 4?", "12", "24", "16", "B"],
  ["What is 30 + 4?", "32", "24", "34", "C"],
  ["What is 10 + 6?", "12", "14", "16", "C"]
];
function _(x) {
  return document.getElementById(x);
}
function renderQuestion() {
  test = _("test");
  if (pos >= questions.length) {
    test.innerHTML = "<h2>You got " + correct + " of " + questions.length + " Questions correct</h2>";
    _("test_status").innerHTML = "Test Completed";
    pos = 0;
    correct = 0;
    return false;
  }
  _("test_status").innerHTML = "Question " + (pos + 1) + " of " + questions.length;
  question = questions[pos][0];
  chA = questions[pos][1];
  chB = questions[pos][2];
  chC = questions[pos][3];
  test.innerHTML = "<h3>" + question + "</h3>";
  test.innerHTML += "<input type='radio' name='chioces' value='A'> " + chA + "<br>";
  test.innerHTML += "<input type='radio' name='chioces' value='B'> " + chB + "<br>";
  test.innerHTML += "<input type='radio' name='chioces' value='C'> " + chC + "<br>";
  test.innerHTML += "<button onclick='checkAnswer()'>Submit Answer</button>";
}
function checkAnswer() {
  choices = document.getElementsByName("choices");
  for (var i = 0; i < choices.length; i++) {
    if (choices[i].checked) {
      choice = choices[i].value;
    }
  }
  if (choice == questions[pos][4]) {
    correct++;
  }
  pos++;
  renderQuestion();
}
window.addEventListener("load", renderQuestion, false);
<div id="test_status"></div>
<div id="test"></div>

简单调试语句

choices = document.getElementsByName("choices");
console.log(choices)

将显示不返回任何元素。

为什么! ?因为你拼错了选项。

name='chioces'