-1

大家好,我需要一些帮助。我想做的是计算答案的数量。“qu”是问题,“ca”是正确答案。我需要得到数组中的答案数量

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;
    }
}

任何帮助都是极好的!

4

5 回答 5

2

根据我对问题的理解。您需要使用questions[0][cax]而不是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;
    }
}

演示

于 2013-10-29T15:12:30.667 回答
0

假设我正确理解了您的问题,并且您想知道数组“问题”中有多少元素:

问题中的元素数量可以通过使用 获得questions.length

于 2013-10-29T15:13:37.480 回答
0

我假设很多事情 - 但这可能是你正在寻找的

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

不适用于旧浏览器 Doc here

于 2013-10-29T15:15:11.233 回答
0

像这样的东西我认为是你想要的。

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);
于 2013-10-29T15:16:13.307 回答
0

这是你的答案:

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");
于 2013-10-29T15:19:17.927 回答