我正在尝试生成一个测验,当页面重新加载时,它将显示6个数组中的3个随机问题。
测验有效,但以相同的顺序显示所有问题,我希望只有3个随机问题
我使用的代码如下:
var pos = 0, test, test_status, question, choice, choices, chA, chB, chC, correct = 0;
var questions = [
["Question 1", "1", "2", "3", "C"],
["Question 2", "X", "Y", "Z", "B"],
["Question 3", "4", "5", "6", "C"],
["Question 4", "A", "B", "C", "A"],
["Question 5", "7", "8", "9", "B"],
["Question 6", "M", "N", "O", "A"]
];
function get(x){
return document. getElementById(x);
}
function renderQuestion(){
test = get("test");
if(pos >= questions.length){
test.innerHTML = "You got " +correct+ " of "+questions.length+" questions correct";
get("test_status").innerHTML = "Test Completed";
pos = 0;
correct = 0;
return false;
}
get("test_status").innerHTML = "Question " + (pos+1) + " of " + questions.length;
question = questions[pos] [0];
chA = questions[pos][1];
chB = questions[pos][2];
chC = questions[pos][3];
test.innerHTML = "" +question+" <br>";
test.innerHTML += "<input type='radio' name ='choices' value ='A'> " +chA+"<br>";
test.innerHTML += "<input type='radio' name ='choices' value ='B'> " +chB+"<br>";
test.innerHTML += "<input type='radio' name ='choices' value ='C'> " +chC+"<br><br>";
test.innerHTML += "<button onclick='checkAnswer()' >Submit Answer</button>";
}
function checkAnswer(){
choices = document.getElementsByName('choices');
for (var i = 0; i < choices.length; i++) {
if(choices[i].checked){
choice = choices[i].value;
}
}
if (choice == questions [pos][4]) {
correct++;
}
pos++;
renderQuestion();
}
window.addEventListener("load", renderQuestion, false);
发布于 2016-03-29 23:56:26
您可以尝试如下所示:
var questions = [
["Question 1", "1", "2", "3", "C"],
["Question 2", "X", "Y", "Z", "B"],
["Question 3", "4", "5", "6", "C"],
["Question 4", "A", "B", "C", "A"],
["Question 5", "7", "8", "9", "B"],
["Question 6", "M", "N", "O", "A"]
];
var display = getRandomValues(questions,3);
print(display);
function getRandomValues(arr, count){
// Create a copy so you do not modify original array
var _tmp = arr.slice();
var result = [];
// Loop based on count
for(var i=0; i<count; i++){
// Calculate a random number and round it. Take Mod based on array.length
var random = Math.floor(Math.random() * 10) % _tmp.length;
// Push necessary item in array to be returned.
result.push(_tmp[random]);
// Remove item that has been added to prevent duplicate entries
_tmp.splice(random,1);
}
return result;
}
function print(arr){
document.write("<pre>" +JSON.stringify(arr,0,4)+ "</pre>");
}
另外,我建议您使用对象数组而不是数组数组
var questions = [
{title:"Question 1", options:["1", "2", "3", "C"]},
{title:"Question 2", options:["X", "Y", "Z", "B"]},
{title:"Question 3", options:["4", "5", "6", "C"]},
{title:"Question 4", options:["A", "B", "C", "A"]},
{title:"Question 5", options:["7", "8", "9", "B"]},
{title:"Question 6", options:["M", "N", "O", "A"]}
];发布于 2016-03-29 23:54:58
也许this可以用来生成一个随机数。您可能希望生成一个介于0和5之间的值,但仍然如此。当然,如果你不想同一个问题被问两次,那么你需要跟踪哪些问题已经被问过了。
https://stackoverflow.com/questions/36289095
复制相似问题