Java Reference
In-Depth Information
Quiz Ninja Project
Now we've reached the end of the chapter, so it's time to use what we have learned to add
some features to our Quiz Ninja project. Open up scripts.js in the js folder.
We'll start by creating a nested array called quiz that contains all the questions and answers.
Each item will be another array that contains the question as its first item and the answer as
its second item:
scripts.js (excerpt)
var quiz = [
["What is Superman's real name?","Clarke Kent"],
["What is Wonderwoman's real name?","Dianna Prince"],
["What is Batman's real name?","Bruce Wayne"]
];
Next, we create and initialize a variable called score to keep track of how many correct
answers the player has given:
scripts.js (excerpt)
var score = 0 // initialize score
Then we loop through the quiz array, asking each question using a prompt dialog that al-
lows the player to enter an answer which is stored in a variable called answer . We can then
compare this to the actual answer stored in the quiz array:
scripts.js (excerpt)
for(var i=0,max=quiz.length;i<max;i++){
// get answer from user
var answer = prompt(quiz[i][0]); // quiz[i][0] is the ith
question
// check if answer is correct
if(answer === quiz[i][1]){ // quiz[i][1] is the ith answer
alert("Correct!");
Search WWH ::




Custom Search