Javascript 使用for循环动态打印多维数组元素
我正在编写一个javascript程序来动态打印多维数组的元素,以创建一个测验。我的结构是正确的,但我正在尝试打印“选择”元素,以便它们显示为每个问题选择的单选按钮 Javascript:Javascript 使用for循环动态打印多维数组元素,javascript,html,Javascript,Html,我正在编写一个javascript程序来动态打印多维数组的元素,以创建一个测验。我的结构是正确的,但我正在尝试打印“选择”元素,以便它们显示为每个问题选择的单选按钮 Javascript: var dataquestions = []; dataquestions[0] = {question: "Who is the prime Minister of the United Kingdom?", choice0: "David Cameron", choice1: "Tony Bla
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>';
}
}
你不能使用
dataquestions[i].choice+j
以访问对象的属性。但是,您可以使用下标符号,如下所示
dataquestions[i]["choice" + j]
使用
这部分代码:
dataquestions[i].choice+j
将计算为数据问题[i].choice
和j
的串联,这实际上是未定义+j
。要引用动态命名的属性,必须将'choice'
和j
连接起来,然后使用[]
取消引用,因此数据问题[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');
对于(var i=0;i
';
对于(var j=0;j;
}
container.innerHTML+=html;
}
工作得很好!谢谢大家!@杰夫普。不客气:)请忘记不要勾选这个答案:)很好,@thefourtheye。如果这个答案回答了你的问题,你应该接受。作为其他用户的未来参考@jeff-p@NullSoulException我想OP已经意识到了:)这太好了@jack。我已经有一段时间没有使用JavaScript了,但是看着这些答案可以更新我的技能这是一个很好的结构,但它只是打印出最后一个问题。
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;
}