javascript - 尝试使用 for 循环和 while 的琐事问题

标签 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;
}

最佳答案

在这种特殊情况下,将代码拆分为函数对我来说没有意义:

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)

关于javascript - 尝试使用 for 循环和 while 的琐事问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46283753/

相关文章:

javascript - 将外部数据从数据库动态加载到 d3.js

javascript - 如何在javascript中为访问 token 生成oauth1签名?

javascript - Colorbox scalePhotos 不工作

javascript - 使用 AngularJS 更改工厂中的 URL 输入值

javascript - 可以使用 SignalR 向特定用户发送消息吗?

Javascript onClick 不适用于多种表单

javascript - 实现正则表达式以在 javascript 文件中查找带有类的 span

javascript - Google 图表 - 更改 'more' 链接的颜色

javascript - .append() 方法仅追加一半的项目

javascript - svg文本元素内的不可见文本