2014-03-03 93 views
2

我正在寫一個JavaScript程序來動態地打印多維數組的元素來創建測驗。我的結構是正確的,但我試圖打印'選擇'元素,因此它們顯示爲用於選擇每個問題的單選按鈕。使用for循環動態打印多維數組元素

的Javascript:

var dataquestions = []; 

dataquestions[0] = {question: "Who is the prime Minister of the United Kingdom?",  choice0: "David Cameron", choice1: "Tony Blair", choice2:"Gordon Brown", answer:"David Cameron"}; 

dataquestions[1] = {question:"In what year was the Declaration of Independence signed?", choice0:"1985", choice1:"1492", choice2:"1776", answer:"1776"}; 

dataquestions[2] = {question:"Which country is in Europe?", choice0:"Pakistan", choice1:"France", choice2:"Australia", answer:"France"}; 

for (var i=0; i<=2; i++) 
{ 
document.getElementById('quizcontain').innerHTML+= '<p>'+ dataquestions[i].question+'</p><br><br>'; 

for (var j=0; j<=2; j++){ 
document.getElementById('quizcontain').innerHTML+='<input type="radio" name='+j+'>'+dataquestions[i].choice+j+'<br>'; 
    } 
} 

輸出:

Who is the prime Minister of the United Kingdom? 

undefined 
undefined 
undefined 
In what year was the Declaration of Independence signed? 

undefined 
undefined 
undefined 
Which country is in Europe? 

undefined 
undefined 
undefined 

回答

1

不能使用

dataquestions[i].choice+j 

訪問對象的屬性。但是,你可以使用標符號,像這樣

dataquestions[i]["choice" + j] 
+1

完美地工作!謝謝! –

+0

@JeffP。歡迎您:)請忘記不要打勾這個答案:) – thefourtheye

+0

不錯,@thefourtheye。 – zee

0

使用

dataquestions[i]["choice" + j] 
1

你的這部分代碼:

dataquestions[i].choice+j 

獲取評估的dataquestions[i].choicej串聯,這實際上是undefined + j。要引用一個動態命名的屬性,您必須連接'choice'j,然後使用[]取消引用,所以dataquestions[i]['choice' + j]

其次,這將是一件好事,一定要規範你的數據結構:

var dataquestions = [{ 
    question: "Who is the prime Minister of the United Kingdom?", 
    choices: ["David Cameron", "Tony Blair", "Gordon Brown"], 
    answer: 0 
}, { 
    question: "In what year was the Declaration of Independence signed?", 
    choices: ["1985", "1492", "1776"], 
    answer: 2 
}, { 
    question:"Which country is in Europe?", 
    choices: ["Pakistan", "France", "Australia"], 
    answer: 1 
}]; 

然後:

var container = document.getElementById('quizcontain'); 
for (var i=0; i < dataquestions.length; i++) { 
    var question = dataquestions[i], 
    html; 

    html = '<p>' + question.question + '</p><br><br>'; 

    for (var j = 0; j < question.choices.length; ++j) { 
     html += '<input type="radio" name="' + j + '">' + question.choices[j] + '<br>'; 
    } 

    container.innerHTML += html; 
} 

Demo

+0

這是完美的@jack。自從我使用JavaScript以來已經有一段時間了,但是查看這些答案會刷新我的技能 – zee

+0

這是一個很棒的結構,但它只是打印出最後一個問題。 –

+0

@JeffP。糟糕,錯誤:)更新。 –