在Javascript中以增量顺序显示问题列表

时间:2017-05-06 15:13:35

标签: javascript

我确实有问题列表,我希望以顺序方式显示。当前代码以随机顺序显示问题。你能帮我按顺序显示所有问题吗?这是代码:

function questionconstructor(question, answers, correctanswer){
    this.question = question;
    this.answers = answers;
    this.correctanswer = correctanswer;
}
var q1 = new questionconstructor('what do you want to do?', ['Job','WFH', 'Business'], 2);
var q2 = new questionconstructor('Where do you want to go?', ['USA', 'UK', 'JAP'], 1);
var q3 = new questionconstructor('Which car do you use?', ['Audi', 'BMW', 'Honda'], 0);
var questions = [q1, q2, q3];

questionconstructor.prototype.displayquestion = function(){
    console.log(this.question);
    for (var i=0; i < this.answers.length; i++){
        console.log(i + ':' + this.answers[i]);
    }
}
questionconstructor.prototype.checkanswer = function(ans){
    if(ans === this.correctanswer){
        console.log("Correct Answer!")
    }else{
        console.log("Try Again!")
    }
}
function displaynextque(){
var rand = Math.floor(Math.random() * questions.length);
console.log(rand);
questions[rand].displayquestion();
    var answerofperson = prompt("please select your answer!")
    if (answerofperson !== 'exit'){
        questions[rand].checkanswer(parseInt(answerofperson));
        displaynextque();
    }
}
displaynextque();

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用全局index变量并在小于长度的情况下递增它。

&#13;
&#13;
function questionconstructor(question, answers, correctanswer) {
    this.question = question;
    this.answers = answers;
    this.correctanswer = correctanswer;
}

questionconstructor.prototype.displayquestion = function () {
    console.log(this.question);
    for (var i = 0; i < this.answers.length; i++) {
        console.log(i + ':' + this.answers[i]);
    }
}
questionconstructor.prototype.checkanswer = function (ans) {
    if (ans === this.correctanswer) {
        console.log("Correct Answer!")
    } else {
        console.log("Try Again!")
    }
}

function displaynextque() {
    questions[index].displayquestion();
    var answerofperson = prompt(questions[index].question + ' (' + questions[index].answers.map(function (a, i) { return [i, a].join(': '); }).join(', ') + '):')
    if (answerofperson !== 'exit') {
        questions[index].checkanswer(parseInt(answerofperson));
        index++;
        if (index < questions.length) {
            displaynextque();
        }
    }
}

var q1 = new questionconstructor('what do you want to do?', ['Job', 'WFH', 'Business'], 2),
    q2 = new questionconstructor('Where do you want to go?', ['USA', 'UK', 'JAP'], 1),
    q3 = new questionconstructor('Which car do you use?', ['Audi', 'BMW', 'Honda'], 0),
    questions = [q1, q2, q3],
    index = 0;

displaynextque();
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;