Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Jess Taylor
5,160 PointsMy Solution
function playAgain() {
var choice = prompt('Do you want to play again?');
choice = choice.toLowerCase();
if ( choice === 'yes' || choice === 'y' ) {
return true;
} else {
return false;
};
}
function askQuestions() {
for ( i = 0; i < questions.length; i++ ) {
var answer = prompt('Q' + (i + 1) + '.' + questions[i][0]);
answer = answer.toLowerCase();
if ( answer === questions[i][1] ) {
questionsCorrect.push(questions[i][0]);
} else {
questionsWrong.push(questions[i][0]);
};
}
}
function printResults() {
if (questionsCorrect.length > 0 ) {
document.write('<h2>You got these questions right</h2><ol>');
for ( i = 0; i < questionsCorrect.length; i++ ) {
document.write('<li>' + questionsCorrect[i] + '</li>');
}
document.write('</ol>');
};
if (questionsWrong.length > 0 ) {
document.write('<h2>You got these wrong though..</h2><ol>');
for ( i = 0; i < questionsWrong.length; i++ ) {
document.write('<li>' + questionsWrong[i] + '</li>');
}
document.write('</ol>');
};
}
var questions = [
['What colour is the sky?', 'blue'],
['What colour is the sun?', 'yellow'],
['What colour is the grass?', 'green'],
['What colour is snow?', 'white'],
['What colour is wood?', 'brown']
];
do {
var correctAnswers = 0;
var questionsWrong = [];
var questionsCorrect = [];
askQuestions();
document.write("<br><p>Congratulations you got " + questionsCorrect.length + " correct answer(s)!</p>");
printResults();
} while ( playAgain() )
This is my solution, I feel like it is a little long winded! But i tried to break it down into a few little functions so that I can expand it in the future.
Thoughts?? :)
2 Answers
John Steer-Fowler
Courses Plus Student 11,734 PointsHi Jess,
It doesn't run for me :(
Have you tested it?
Mark Casavantes
Courses Plus Student 13,401 PointsHi Jess and John,
The program is missing the HTML needed to run in a browser. It looks like Code Pen lets you run code with just JavaScript.
Jess Taylor
5,160 PointsJess Taylor
5,160 PointsHi,
Yes it works fine for me :/ just tested it in codepen
http://codepen.io/jessicatee/pen/pjjMWZ
John Steer-Fowler
Courses Plus Student 11,734 PointsJohn Steer-Fowler
Courses Plus Student 11,734 PointsAh, it works in Codepen :D
Very nice. I'm not a JS expert but it looks good to me.
Keep up the good work