使用for循环动态打印多维数组元素

时间:2014-03-03 05:11:58

标签: javascript html

我正在编写一个javascript程序来动态打印多维数组的元素以创建测验。我的结构是正确的,但我正在尝试打印“选择”元素,以便它们显示为单选按钮,用于选择每个问题。

使用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

3 个答案:

答案 0 :(得分:1)

你不能使用

dataquestions[i].choice+j

访问对象的属性。但是,您可以使用下标表示法,例如

dataquestions[i]["choice" + j]

答案 1 :(得分:1)

这部分代码:

dataquestions[i].choice+j

获取评估为dataquestions[i].choicej的串联,实际上是undefined + j。要引用动态命名的属性,您必须连接'choice'j,然后使用[] dereferencsing,因此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

答案 2 :(得分:0)

使用

dataquestions[i]["choice" + j]