超级简单的测验计划。我的答案没有验证,得分也不是+ ++

时间:2015-08-27 02:34:38

标签: javascript html css arrays

我正在为练习写这个超级简单的javascript测验。我很沮丧,因为我认为我的代码是正确的,但我的代码不起作用。

我的答案不是'验证'我不知道为什么。我的分数仍然是0.我的分数不是得分++应该......

问题在于此片段:

 for (var j = 0; j <= total.length; j++) {
    if (questionArray[j] === answers[j]) {
      score = score + 1;
    }
  }

JS:

function submitAnswers() {

  //Set score and total number of questions
  var total = 5;
  var score = 0;
  //Get user input for each question
  var q1 = document.forms['quizForm']['q1'].value.toString();
  var q2 = document.forms['quizForm']['q2'].value.toString();
  var q3 = document.forms['quizForm']['q3'].value.toString();
  var q4 = document.forms['quizForm']['q4'].value.toString();
  var q5 = document.forms['quizForm']['q5'].value.toString();

  //Load Questions into Question Array
  var questionArray = [q1, q2, q3, q4, q5];

  //Validation
  for (var i = 0; i <= questionArray.length; i++) {
    if (questionArray[i] === null || questionArray[i] === '') {
      alert("Oops!  You forgot to answer a question.  Please enter an answer for Question " + [i + 1] + ".");
      return false;
    }
  }


  //Set correct Answers
  var answers = ["b", "a", "d", "b", "d"];

  //Check for correct answers
  for (var j = 0; j <= total.length; j++) {
    if (questionArray[j] === answers[j]) {
      score = score + 1;
    }
  }
  alert("You scoreed "+ score+ " out of "+total);



  return false;
}

JSFiddle:https://jsfiddle.net/jeffward01/1y3dxk0s/

2 个答案:

答案 0 :(得分:2)

用于验证部分:

  for (var i = 0; i <= questionArray.length; i++)

应该是

  for (var i = 0; i < questionArray.length; i++)

答案部分:

 for (var j = 0; j <= total.length; j++)

应该是

 for (var j = 0; j < answers.length; j++)

答案 1 :(得分:1)

变化:

for (var j = 0; j < total.length; j++) {

for (var j = 0; j < total; j++) {

总和是你想要的值,而不是total.length。

<强> jsFiddle example