本文介绍了Javascript随机测验,但超过1问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经制作了这个代码,每次刷新或点击页面时都会显示一个随机问题。但是,我希望它不仅显示一个随机问题,而且每次随机显示3个不同的问题。我该怎么做!
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!
谢谢!
<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>
推荐答案
这样可行。
<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>
这篇关于Javascript随机测验,但超过1问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!