JavaScript变量不会因条件

时间:2017-10-03 03:06:20

标签: javascript

有些人请解释我是如何在每次正确回答问题时将得分变量添加到其中的。每当我运行它时,当我正确回答时,我得到零分。感谢。

var questions = [
['What is 1+1?', 2],
['What is 2+2?', 4],
['What is 4+4?', 8],
];

var score = 0;

for(var i=0; i<questions.length; i++)
    {
    var response = prompt(questions [i][0]);
    var correctAnswer = questions[i][1];
    if (response === correctAnswer)
    {
      score += 1;

    } 

    }
document.write('Your score is '+score);


function print(message) {
  document.write(message);
}

3 个答案:

答案 0 :(得分:1)

parseInt提示中的结果因为你想要的是一个数字..

&#13;
&#13;
var questions = [
['What is 1+1?', 2],
['What is 2+2?', 4],
['What is 4+4?', 8],
];

var score = 0;

for(var i=0; i<questions.length; i++)
    {
    var response = parseInt(prompt(questions[i][0]));
    var correctAnswer = questions[i][1];
    if (response === correctAnswer)
    {
      score++;

    } 

    }
document.write('Your score is '+score);


function print(message) {
  document.write(message);
}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

可能是因为提示的响应是字符串&amp;你正在与数字进行比较。使用的一元运算符(+)在比较之前转换为数字

&#13;
&#13;
var questions = [
  ['What is 1+1?', 2],
  ['What is 2+2?', 4],
  ['What is 4+4?', 8],
];

var score = 0;

for (var i = 0; i < questions.length; i++) {
  var response = prompt(questions[i][0]);
  var correctAnswer = questions[i][1];
   //CHanged here
  if (correctAnswer === +response) {
    score += 1;
  }
}
document.write('Your score is ' + score);


function print(message) {
  document.write(message);
}
&#13;
&#13;
&#13;

答案 2 :(得分:0)

提示返回一个字符串,您在数组中的答案将存储为数字。要么更改字符串的答案,要么使用==而不是===来检查是否相等。使用double equals将允许Javascript引擎灵活地使用类型。