大家好,我需要一些帮助。我想要做的是计算答案的数量。 “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;
}
}
任何帮助都会很棒!
答案 0 :(得分: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;
}
}
答案 1 :(得分:0)
假设我正确理解了您的问题,并且您想知道数组中存在多少元素“问题”:
使用questions.length
可以获得问题中元素的数量。
答案 2 :(得分:0)
我假设很多东西 - 但这可能就是你要找的东西
for(var i=0; i < questions.length; i++)
{
console.log("Number of answers for Question No." + i + " - " + Object.keys(questions[i]).length - 1);
}
不适用于旧浏览器 文件here
答案 3 :(得分: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);
答案 4 :(得分: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");