Java Reference
In-Depth Information
"asked":
↵
false }
]
}
You might like to add some extra questions to the
questions
array as well, as it will
make the game more interesting to have more than three options!
Because we're no longer working through the questions one at a time, instead of using
i
to track which question we are asking, we'll use a variable called
question
to store the
current question object. This means that we need to replace the following line:
var i = 0;
with this line that declares the
question
variable:
var question; // current question
This line only declares the
question
variable; it is set in the
chooseQuestion()
function that we'll update next:
function chooseQuestion() {
console.log("chooseQuestion() called");
var questions = quiz.questions.filter(function(question){
return question.asked === false;
});
// set the current question
question = questions[random(questions.length) - 1];
ask(question);
}
Here we're using the
filter()
array method to return another array containing only the
questions that have a value of
false
for their
asked
property, so they are yet to be asked.
The
random()
function is then used to select a random number between
1
and the length
of this array. We then subtract
1
from this value and use it as the index to select the ques-
tion to ask by assigning it to the
question
variable. This is then passed to the
ask()
function as an argument.
