I wrote a program which asks the user a series of questions and determines whether the answer entered by the user is correct or incorrect. Example:
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");
}
...
I plan on displaying how many questions the user answered correctly after all of the questions are asked. Suppose the code goes on this way until question10. how would I use the Math.random() function so that the questions are asked in random order?
This can help you get started.
https://jsfiddle.net/wwnzk6z9/1/
Psuedo-code explanation:
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.