Переменная внутри цикла не увеличивается на единицу - PullRequest
0 голосов
/ 10 июля 2019

Переменная rightAnsNum не увеличивается циклом for!Я хочу, чтобы переменная 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 голосов
/ 10 июля 2019

Как предложил 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;
}
...