Javascript random quiz but more than 1 asked

2019-06-11 01:43发布

问题:

I have made this code which displays a random question each time a page is refreshed or clicked. However, i want it to display not just one random question but 3 different ones which are randomized each time. How would i do this!

Thanks!

<script language="JavaScript"> 
        var question= new Array(5)
        question[0] = "Question 1"
        question[1] = "Question 2"
        question[2] = "Question 3"
        question[3] = "Question 4 "
        question[4] = "Question 5) "
        question[5] = "Question 6) "
        var rand_int= Math.floor(Math.random()*5);

        document.write(question[rand_int]);
        </script>

回答1:

This works.

<script language="JavaScript"> 

var question= new Array(5)
question[0] = "Question 1"
question[1] = "Question 2"
question[2] = "Question 3"
question[3] = "Question 4"
question[4] = "Question 5"
question[5] = "Question 6"

var numberOfQuestions = 3;
var questions = [];

for(var i=0;i<numberOfQuestions;i++){
    var rand_int= Math.floor(Math.random()*question.length);
          while(question[rand_int] == null){
    var rand_int= Math.floor(Math.random()*question.length);
    }
    questions.push(question[rand_int]);
    question.splice(rand_int, 1);
}

for (var i = 0; i < questions.length; i++) {
    document.write(questions[i] + "<br />");
}


</script>


回答2:

Firstly, I would stay away from document.write -- this overwrites the page each time. Instead you should append to a DOM element.

<div id="questionsContainer"></div>

Assign this div to a variable:

var questionDiv = document.getElementById("questionDiv");

You'll need a new random number each time one of the questions from the list is pulled. Define the number of questions you want to show:

var questionsVisible = 3;

Loop over the array of questions with the questionsVisible as the stopping point:

for (var i = 0; i < questionsVisible; i++) {
    var rand_int = Math.floor(Math.random() * question.length); //use the length of the array, not a magic number

    //Create and append
    var span = document.createElement("span");
    span.text = question[rand_int];
    questionDiv.appendChild(span);

    //Splice the used question
    question.splice(rand_int, 1);
}