Trivia问题与for循环和while

时间:2017-09-18 16:04:17

标签: javascript

我在尝试显示存储在阵列上的问题和答案时遇到了一些问题,同时尝试循环。但是,问题似乎没有出现,或存储用户输入。

有人可以查看我的代码并指导我做错了什么吗?我将非常感谢所有的帮助

<script>
//display questions on js stored on array
displayQuestions();

var userInfo = prompt(questions[0]);
var userInfo = prompt(questions[1]);
var userInfo = prompt(questions[2]);
var answers = findAnswers(userInfo);

if(answers == "Wrong"){
    document.write("<p>" + userInfo + "is " + answers + "</p>")
} else {
    document.write("<p>" + userInfo + "is right""</p>");
}

var score = triviaQuestions();
document.write('Your score is ' +score);
</script>

这里是我的js代码,其中我有数组,我正在尝试创建一个接受一个参数即计数器的测验函数。这将初始化3的猜测变量。这将用于倒计时用户必须正确回答问题的尝试次数。

var questions = ['What is the first day of the week?','what is last day of 

the week?',
'What is better, an Xbox or Playstation?'];

var answers = ['Monday', 'sunday','xbox'];


function displayQuestions(){
    for(i = 0; i < 2; i++){
        document.write(questions[i]);
        document.write("<br>");
    }
}

function findAnswers(match){
    i =0;
    while (i < 2) {
        if (questions[i] == match){
            return answers[i];
        } else {
            i++;
        }
    }
    return "Wrong Answer";
}


function triviaQuestions() {
    var score = 0;

    for (i = 0; i < 3; i++){
        var attempts = 3;

        while(attempts > 0) {
            ans = promt(+questions[i]);

            if(ans == answers[i]){
                score = score + 1;
                alert("Good Job");
                attempts = 0;
            } else {
                alert("Wrong!");
                attempts = attempts - 1;
            }
        }
    }
    return score;
}

1 个答案:

答案 0 :(得分:1)

在这种特殊情况下,将代码拆分为函数是没有意义的:

var score = 0;
const questions = [
  'What is the first day of the week?',
  'what is last day of the week?',
  'What is better, an Xbox or Playstation?'
];
const answers = ['Monday', 'sunday','xbox'];


questions.forEach( function(question, i){
  var triesLeft = 3;
  while(triesLeft--){
    if( prompt(question) === answers[i] ){
       alert("right!");
       score++;
       return;// continue with forEach
    }
    alert("please try again!");
  }
  alert("sorry, you had the chance :/");
});

alert("you did a score of "+score);

(forEach可以用常规for循环替换。但是,然后需要使用else)