Tallying incorrect answers for Javascript game

时间:2015-06-15 15:14:35

标签: javascript for-loop

So I am trying to make a javascript game for my geography class but I have run into some trouble, I can ask the questions and tell you if you're wrong or not but I would like to be able to keep track of the wrongs answers. I want to keep track using for loops but I'm not good at them, some help would be greatly appreciated!

This is the basis of what every question looks like, it's just that && is where I need to add a single mark to the incorrect tally which I am sure I need to use for loops for.

var y = "You are correct!!!"
var n = "You are incorrect!!!"

alert("Chapter 1, Human Cultural Connections. 1-10")
//==================================================
var Q1 = prompt("Demographers identify three different stages of life. 
They are children, working adults, and older adults. What is the age 
range for children? 0-13, 0-15, 0-18")

if (Q1 === "0-13")
{
alert(y)
}
else
{
alert(n) //&& add 1 tally to incorrect list
}

If someone could help me out with this it would be sooo helpful, and don't worry this is past do anyways but I still want to know how to do it for future projects!

p.s. I already have the script HTML so I don't need help with that.

2 个答案:

答案 0 :(得分:2)

var correct = [], // well store the index of the correctly answered questions here
    wrong = [], // well store the index of the incorrectly answered questions here
    questions = [
    {
        "question": "Demographers identify three different stages of life. They are children, working adults, and older adults. What is the age range for children?",
        "answers": ["0-13", "0-15", "0-18"],
        "correct": 0 // correct answer is item of index 0 in property "answers" (0-13)
    },
    {
        "question": "whats your favorite color?",
        "answers": ["red", "yellow", "blue", "purple"],
        "correct": 2 // blue
    }
];

for (var i in questions){
    var answer = prompt(questions[i].question + questions[i].answers.join(','));
    if (answer == questions[i].answers[questions[i].correct]){
        correct.push(i);
    }else{
        wrong.push(i);
    }    
}

alert('wrong number of answers: ' + wrong.length);
alert('correct number of answers: ' + correct.length);
alert('first wrong question: ' + questions[wrong[0]].question);

我知道这实际上是你要求的过度设计,但它可能会给你更好的灵活性和知识,以了解循环的js如何工作。希望它有所帮助。

答案 1 :(得分:1)

Add a variable to keep track of incorrect answers:

var y = "You are correct!!!"
var n = "You are incorrect!!!"
var incorrectCount = 0;

alert("Chapter 1, Human Cultural Connections. 1-10")
//==================================================
var Q1 = prompt("Demographers identify three different stages of life. 
They are children, working adults, and older adults. What is the age 
range for children? 0-13, 0-15, 0-18")

if (Q1 === "0-13")
{
alert(y)
}
else
{
alert(n) //&& add 1 tally to incorrect list
incorrectCount++;
}