JSFiddle - React, Tailwind, and code Playground
by Susanna You
HTML
<div id="output"></div>
JavaScript
var questions = [
['How many states are in the United States?', 50],
['How many continents are there?', 7],
['How many legs does an insect have?', 6],
['How many legs are on a table?', 4]
];
var randomQuestion;
var correctAnswers = 0;
var question;
var answer;
var response;
var correct = [];
var wrong = [];
//print function for outputing in HTML
function print(message) {
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = message;
}
function buildList(arr) {
var listHTML = '<ol>';
for (var i = 0; i < arr.length; i++) {
listHTML += '<li>' + arr[i] + '</li>';
}
listHTML += '</ol>';
return listHTML;
}
//Problem: Need questions to prompt randomly.
//Solutution: Need a function to randomize questions.
/**
//Make function that randomizes questions
function getRandomQuestion() {
var randomQuestion = Math.floor(Math.random() * questions.length) + 1;
return randomQuestion;
}
**/
//Use the random output to prompt the random questions
//Looping through all questions
for (var i = 0; i < questions.length; i += 1) {
randomQuestion = Math.floor(Math.random() * questions.length) + 1;
question = randomQuestion(questions[i][0]);
answer = randomQuestion(questions[i][1]);
response = prompt(question);
response = parseInt(response);
if (response === answer) {
correctAnswers += 1;
correct.push(question);
} else {
wrong.push(question);
}
}
html = "You got " + correctAnswers + " question(s) right."
html += '<h2>You got these questions correct:</h2>';
html += buildList(correct);
html += '<h2>You got these questions wrong:</h2>';
html += buildList(wrong);
print(html);