2014-03-03 4 views
2

나는 다차원 배열의 요소를 동적으로 인쇄하여 퀴즈를 작성하는 자바 스크립트 프로그램을 작성 중입니다. 내 구조는 정확하지만 '선택'요소를 인쇄하여 각 질문의 선택을위한 라디오 버튼으로 표시하려고합니다.for 루프를 사용하여 다차원 배열 요소를 동적으로 인쇄

자바 스크립트 :

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].choicej의 연결로 평가 가져옵니다

dataquestions[i].choice+j 

하는 효과적으로 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

깔끔한 @ 잭. 자바 스크립트를 사용 했으므로 잠시 지났지 만 논문을 보는 것이 내 기술을 새롭게 함 – zee

+0

이것은 훌륭한 구조이지만 마지막 질문 만 인쇄합니다. –

+0

@JeffP. 죄송합니다. 버그 : 업데이트되었습니다. –

관련 문제