二维数组,If .. Else语句没有正确执行。

时间:2017-11-21 20:05:03

标签: javascript

var correct = 0;
var wrong = 0;
var questions = [
    ["How many months are there in a year?", 12 ],
    ["What is my favorite vacation spot?", "Costa Rica"],
    ["How old am I?", 23]
];

for(var i = 0; i < questions.length; i ++ ) {
  prompt(questions[i][0]);
}  
if (questions[0][1] === 12 ) {
  print("Correct!");
  correct += 1;
  } else {
    wrong += 1;
  }

if(questions[1][1] === "Costa Rica") {
  print("Correct!");
  correct += 1;
  } else {
    wrong += 1;
  }

if(questions[2][1] === 23) {
  print("Correct!");
  correct += 1;
  } else {
    wrong += 1;
  }



print(wrong);

这是我使用JavaScript制作的练习测验。当我测试代码时,我意识到即使我把错误的答案代码仍然执行正确。我尝试从阵列中删除正确的答案,但我不认为这是问题。

2 个答案:

答案 0 :(得分:2)

&#13;
&#13;
var wrong = 0;
var questions = [
  ["How many months are there in a year?", 12, null],
  ["What is my favorite vacation spot?", "Costa Rica", null],
  ["How old am I?", 23, null]
];

for (var i = 0; i < questions.length; i++) {
  questions[i][2] = prompt(questions[i][0]);
}

for (i = 0; i < questions.length; i++) {
  if (questions[i][1] != questions[i][2])
    wrong++;
}

console.log("Wrong: ", wrong);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

另一种实施方式:

&#13;
&#13;
(function() {
  let wrong = 0;
  
  const questions = [
    ["How many months are there in a year?", 12],
    ["What is my favorite vacation spot?", "Costa Rica"],
    ["How old am I?", 23]
  ];
  
  questions.forEach((question, idx, arr) => {
    question.push(window.prompt(question[0]));
    wrong += (question[1] != question[2]) ? 1 : 0;
  });
  
  window.alert(`Wrong: ${wrong}`);
})();
&#13;
&#13;
&#13;

这并不是说它更正确。只是略有不同的方法。

另外,请注意使用&#34;!=&#34;比较运算符,而不是&#34;!==&#34;。

如果您需要解释两者之间的区别,请参阅this MDN页。