Question

Hello guys I need a little help with this. What I am trying to do is to count the number of answers. "qu" is the question, and "ca" are the corect answers. I need to get the amount of answers in the array

var questions = [{"qu" : "question?","ca0" : "answer1","ca1" : "answer2"}];

I tried something like this but it wasn't working.

for(var i = 0; i< 10;i++)
{
    var cax = "ca" + i;
    if(questions[0].cax == null)
    {
        alert("there are " + (i+1)  + "answers");
        break;
    }
}

Any help would be awesome!

Was it helpful?

Solution

As per my understanding of the problem. You need to use questions[0][cax] instead of questions[0].cax

var questions = [{
    "qu": "question?",
    "ca0": "answer1",
    "ca1": "answer2"
}];
for (var i = 0; i < 10; i++) {
    var cax = "ca" + i;
    if (questions[0][cax] == null) {
        alert("there are " + (i + 1) + "answers");
        break;
    }
}

DEMO

OTHER TIPS

Assuming I understand your question correctly and you want to know how many elements there are in your array "questions":

the number of elements in questions can be obtained by using questions.length.

Something like this I THINK is what you want.

var quiz = {
                questions: [{
                    question: 'what is 2x2?',
                    answer: 5,
                    correctAnswer: 4
                }, {
                    question: 'what is 3x2?',
                    answer: 12,
                    correctAnswer: 6
                }, {
                    question: 'what is 2+4',
                    answer: 6,
                    correctAnswer: 6
                }
                ]
            };
            function gradeQuiz(array) {
                var rightAnswers = 0;
                for (var i = 0; i < array.questions.length; i++) {
                    if (array.questions[i].answer === array.questions[i].correctAnswer) {
                        rightAnswers++;
                    }
                }
                console.log('there were ' + array.questions.length + ' questions');
                console.log('you got ' + rightAnswers + ' correct');
            }

            gradeQuiz(quiz);

Here is your answer:

var questions = [{"qu" : "question?","ca0" : "answer1","ca1" : "answer2"}];

var nCorrect = 0;
for (var i=0; i < questions.length; ++i) {
    var q = questions[i];
    for (var p in q) {
        if (p.indexOf("ca") == 0)
            nCorrect++;
    }
}

alert("There are " + nCorrect + " answers");

I am assuming many things - but this could be what you are looking for

for(var i=0; i < questions.length; i++)
{     
console.log("Number of answers for Question No." + i + " - " +  Object.keys(questions[i]).length  -  1);
}

Won't work on older browsers Doc here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top