JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Build a Quiz Challenge, Part 1 Solution

Omar Morales
Omar Morales
4,786 Points

Another Approach

Hey there community! I decided to do everything I could to try and solve this problem on using my own approach, and when I was done I found out it was very different than Dave's. If you want to see another way of approaching this read and run the code below in JS console. The only thing that didn't work was the break statement. And It may be slightly less efficient than Dave's.

// Code var correctAnswer = 0; var wrongAnswer = 0; var counter = 0; var msg; var correctDisplay = "<ul> " var wrongDisplay = "<ul> "

var contentArray = [ ["What is the capital of Kansas?", "topeka"], ["What pro football team is in located in kansas?", "chiefs"], ["What is my last name?", "morales"] ]

while (counter < 3){ for (i = 0; i < contentArray.length; i++){ msg = prompt(contentArray[i][0]) if (msg === "quit"){ break; } else if (msg.toLowerCase() === contentArray[i][1]) { correctAnswer++ counter++ correctDisplay += "<li>" + contentArray[i][1] + "</li>"
} else { wrongAnswer++ counter++ wrongDisplay += "<li>" + contentArray[i][0] + " </br>the correct answer is: " + contentArray[i][1] + "</li>" } } };

correctDisplay += "</ul>" wrongDisplay += "</ul>" document.write("You have: " + correctAnswer + " correct answers and those were: " + correctDisplay) document.write("You have answered: " + wrongAnswer + " question(s) incorrectly: " + wrongDisplay)

2 Answers

Steven Parker
Steven Parker
203,212 Points

Your approach is basically sound, except that you have redundant nested loops. You don't need the "while" loop or the "counter" variable, and when you remove them the "break" will work as intended.

And it's not a coding issue, but since you didn't use Markdown formatting while posting your lines got smashed together and caused syntax errors. Normally, the "best practice" of putting semicolons after each statement is technically optional; but in this case it could have preserved the functionality.

Stafford Dsouza
Stafford Dsouza
2,566 Points

Even my code was different than Daves. any suggestions or recommendations would be welcome.

function print(message) { document.write(message); }

var quiz = [ ["what is the color of the sky?", "blue"], ["what is the color of an orange?", "orange"], ["what is the color of grass?", "green"] ]

function quizTime(list) { var score = 0; for (i =0; i < list.length; i +=1) { var answer = prompt(list[i][0]); if (answer.toLowerCase() === list[i][1]) { score += 1;
} } print(" you got " + score + " correct out of " + quiz.length + " questions"); } quizTime(quiz);