2013-10-29 77 views
-1

大家好我需要一點幫助。我試圖做的是計算答案的數量。 「qu」是問題,「ca」是核心答案。我需要得到陣列Json array for quiz

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

您需要使用數組的長度,並想在10圈不是一個武斷的數字來開始。 – wootscootinboogie

+0

@wootscootinboogie那麼這不是主要問題,即使我這樣做,它不會工作...而不喜歡我的這篇文章是跛腳...只是說 – Bram

+0

請編輯您的問題,什麼是正確的答案ca0,ca1或ca(某物)? –

回答

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

DEMO

+1

謝謝,這是做的伎倆;)只有現在沒有必要做i + 1。再次感謝! – Bram

+1

@BramDriesen,很高興能幫忙,謝謝您的考慮 – Satpal

0

假設我正確地理解你的問題,你想知道有多少元素出現在你的陣列的「問題」:

數量問題中的元素可以通過使用questions.length獲得。

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

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); 
+0

您可以打開您選擇的瀏覽器的開發人員工具,並在控制檯中查看正確答案。 – wootscootinboogie

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");