我写了一个程序,询问用户一系列问题,并确定用户输入的答案是正确还是不正确。例如:
var questionsCorrect = 0
var question1 = prompt("question 1");
if (question1.toLowerCase() === "answer 1") {
question1 = true;
questionsCorrect += 1;
alert("Correct");
} else {
question1 = false;
alert("Incorrect");
}
var question2 = prompt("question 2");
if (question2.toLowerCase() === "answer 2") {
question2 = true;
questionsCorrect += 1;
alert("Correct");
} else {
question2 = false;
alert("Incorrect");
}
...
我计划在询问所有问题后显示用户正确回答了多少问题。假设代码以这种方式进行,直到问题10。我将如何使用Math.random()函数以便按随机顺序询问问题?
答案 0 :(得分:0)
这可以帮助您入门。
https://jsfiddle.net/wwnzk6z9/1/
Psuedo-code说明:
代码:
var questions = [
'question 1',
'question 2',
'question 3',
'question 4',
'question 5',
'question 6',
'question 7',
'question 8',
'question 9',
'question 10'
]
shuffle(questions)
var index = 0
// assign to window for jsFiddle. You won't need to do this in your code.
window.question = function() {
if (index === 10) {
alert('Complete!')
return;
}
alert(questions[index])
index++
}
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}