Javascript测验游戏 - 从阵列中的八个问题中获取四个随机问题

时间:2018-04-14 12:53:13

标签: javascript

我正在尝试创建一个javascript测验。我按照了这个youtube教程:12。我想要做的是问题是阵列中8个随机问题。我的javascript代码是:

var currentQuestion = 0;
var score = 0;
var totQuestions = questions.length;

var container = document.getElementById("quizContainer");
var questionEl = document.getElementById("question");
var opt1 = document.getElementById("opt1");
var opt2 = document.getElementById("opt2");
var opt3 = document.getElementById("opt3");
var opt4 = document.getElementById("opt4");
var nextButton = document.getElementById("nextButton");
var resultCont = document.getElementById("result");

function loadQuestion (questionIndex) {
    var q = questions[questionIndex];
    questionEl.textContent = (questionIndex + 1) + ". " + q.question;
    opt1.textContent = q.option1;
    opt2.textContent = q.option2;
    opt3.textContent = q.option3;
    opt4.textContent = q.option4;
};

function loadNextQuestion () {
    var selectedOption = document.querySelector("input[type=radio]:checked");
    if(!selectedOption) {
        alert("Please select your answer!");
        return;
    }
    var answer = selectedOption.value;
    if(questions[currentQuestion].answer == answer) {
        score ++;
    }
    selectedOption.checked = false;
    currentQuestion++;
    if(currentQuestion == totQuestions - 1) {
        nextButton.textContent = "Finish";
    }
    if(currentQuestion == totQuestions) {
        container.style.display = "none";
        resultCont.style.display = "";
        resultCont.textContent = "Your Score: " + score;
        return;
    }
    loadQuestion(currentQuestion);
}

loadQuestion(currentQuestion);

我尝试使用math.random()但我唯一能做的就是生成随机数而不是数组中的随机问题。
带有问题的数组如下所示:

{
    "question": "This is question 3",
    "option1": "A",
    "option2": "B",
    "option3": "C",
    "option4": "D",
    "answer": "2"
},
{
    "question": "This is question 4",
    "option1": "A",
    "option2": "B",
    "option3": "C",
    "option4": "D",
    "answer": "1"
}

提前谢谢。

2 个答案:

答案 0 :(得分:1)

下面的代码会从您的数组中获取一个随机项:

var randomQ = questions[Math.round((Math.random()*questions.length)+1)];

答案 1 :(得分:0)

您使用的方法可能会成为问题,因为在选择新问题时不会考虑所有先前提出的问题。你最终可能会重复。

我的建议是首先,生成一个新的有效指标数组作为您的问题集,并在每次要加载新问题时根据需要进行迭代



// I have used a simple array of strings for this demo but it will work for an array of objects too
var questions = ['q1','q2','q3','q4','q5','q6','q8']
function getRandomQuestionSet(number){
    var qSet = [];
    while(qSet.length < number){
        var randomIndex = Math.floor(Math.random()*questions.length);
        if(qSet.indexOf(randomIndex) === -1){
          qSet.push(randomIndex)
        }
    }
    
    return questions.filter(function(d,i){
      return qSet.indexOf(i) > -1;
    })
    
}

// This will have 4 random questions, iterate over this in your `loadQuestion` method
var questionSet = getRandomQuestionSet(4);
console.log(questionSet)
&#13;
&#13;
&#13;