Javascript随机测验,但超过1问

时间:2014-03-16 17:40:40

标签: javascript random

我已经制作了这个代码,每次刷新或点击页面时都会显示一个随机问题。但是,我希望它不仅显示一个随机问题,而且每次随机显示3个不同的问题。我该怎么做!

谢谢!

<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>

2 个答案:

答案 0 :(得分:1)

首先,我会远离document.write - 每次都会覆盖页面。相反,你应该追加到DOM元素。

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

将此div分配给变量:

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

每次拉出列表中的一个问题时,您都需要一个新的随机数。定义要显示的问题数量:

var questionsVisible = 3;

questionsVisible为停止点循环问题数组:

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);
}

答案 1 :(得分:1)

这很有效。

<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>