变量内部循环未增加一

时间:2019-07-10 04:00:20

标签: javascript loops variables return

for循环不会增加变量rightAnsNum! 我希望每次循环内的第一个条件为true时,变量rightAnsNum都会增加。

我尝试返回它,但是循环只运行一次,其余的都不会被读取!

var questions = [
  ['Are penguins white or black? black / white / both', 'both'],
  ['What\'s healthier? pizza / banana', 'banana'],
  ['Is math hard? 0 / 1', '0']
];

var askQuestion;
var rightAnsNum = 0;
console.log(rightAnsNum); // var rightAnsNum is not being summed from the for loop!
var wrongAns = [];
var rightAns = [];

for (var i = 0; i < questions.length; i++) {
  askQuestion = prompt(questions[i][0]);
  askQuestion = askQuestion.toLowerCase();
  if (askQuestion === questions[i][1]) {
    rightAnsNum++; // I tried returning it but the loop only runs once and the rest is not read!
    rightAns.push(questions[i][0]);
  } else {
    wrongAns.push(questions[i][0]);
  }
}

变量rightAnsNum没有增加!

1 个答案:

答案 0 :(得分:0)

如FrankerZ所建议,这与您过早打印rightAnsNum有关。

您可以试试看吗?

var questions = [
    ['Are penguins white or black? black / white / both', 'both'],
    ['What\'s healthier? pizza / banana', 'banana'],
    ['Is math hard? 0 / 1', '0']
  ];

var quizResult = runQuiz(questions)
console.log(quizResult.score)

function runQuiz(questions){
    var quizResult = {
        score : 0,
        rightAns : [],
        wrongAns : []
    }

    for (var i = 0; i < questions.length; i++) {
        askQuestion = prompt(questions[i][0]);
        askQuestion = askQuestion.toLowerCase();
        if (askQuestion === questions[i][1]) {
            quizResult.score++; // I tried returning it but the loop only runs once and the rest is not read!
            quizResult.rightAns.push(questions[i][0]);
        } else {
            quizResult.wrongAns.push(questions[i][0]);
        }  
      } 

      return quizResult;
}