我正在使用Javascript创建一个非常基本的测验应用程序,并想知道嵌套数组/对象的最佳方法是什么。我之前只用简单的一级嵌套做了这个,但觉得这个项目可能需要更多。
测验需要有5个问题,并有多个答案。每个答案都有一个与之相关的分值。当测验完成后,它将取平均值,然后给你一个类型即。 “你很好地勾选了A','你大多选择了B'等等。与你在杂志上的测验类似。
我认为它应该是这样的:
var quizList = {
"question": "What's your favourite Color",
"answers": {
["a","Blue","2"],
["b","Green","4"],
["c","Red","6"],
["d","Orange","8"],
},
"question": "What's your favourite Animal",
"answers": {
["a","Dog","2"],
["b","Cat","4"],
["c","Caterpiller","6"],
["d","Donkey","8"],
}
};
这是正确的,如果是这样,我将如何调用各种数组元素?
答案 0 :(得分:1)
这是正确的
不是真的。这不是一个数组,它是一个包含嵌套对象文字和数组的对象文字。它还包含一个非常大的问题;你用每个新问题/答案覆盖以前的问题/答案键。在对象中不能有两个具有相同名称的属性。你已经有效地做到了这一点:
{ a: 'b', a: 'c' }
将丢弃'b'
并将a
设置为'c'
。
您可能需要重新考虑结构,因此顶级元素是一个数组:
var quizList = [
{
"question": "What's your favourite Color",
"answers": [
["a","Blue","2"],
["b","Green","4"],
["c","Red","6"],
["d","Orange","8"],
]
}, {
"question": "What's your favourite Animal",
"answers": [
["a","Dog","2"],
["b","Cat","4"],
["c","Caterpiller","6"],
["d","Donkey","8"],
]
}
];
...如果是这样,我将如何调用各种数组元素?
你无法“调用”这些数组元素。它们不是可执行代码,它们是愚蠢的数据。您需要编写一个程序,该程序使用此对象作为输入,并生成包含一系列<form>
或<input>
元素的<select>
。
答案 1 :(得分:1)
我相信最好的方法是这样的:
var quizList = [{
question: "What's your favourite Color",
alternatives: [
{ letter: "a", text: "Blue", value: "2" },
{ letter: "b", text: "Green", value: "4" },
{ letter: "c", text: "Red", value: "6" },
{ letter: "d", text: "Orange", value: "8" },
]
}, {
/* other question */
}];
如上所述,您的quizList
不是数组。
答案 2 :(得分:0)
这部分无效:
"answers": {
["a","Dog","2"],
["b","Cat","4"],
["c","Caterpiller","6"],
["d","Donkey","8"],
}
answers
是一个对象(因为{}
),所以它需要有一个键和一个值。也许你的意思是:
"answers": [
["a","Dog","2"],
["b","Cat","4"],
["c","Caterpiller","6"],
["d","Donkey","8"],
]
现在是一个包含4个嵌套数组的数组。
但我宁愿将其更改为:
"answers": [{
letter: "a",
text: "Dog",
value: "2"
},
//...etc
]
通过制作选项对象而不是数组,您可以更加健壮地获取每个答案的属性。所以而不是:
var letter = someAnswer[0]; // is this the right index??
你可以这样做:
var letter = someAnswer.letter; // now I know it's the right one
您的代码将更容易以这种方式维护,您不必记住哪个索引是您的答案的哪一部分。
总的来说,我会选择这样的事情:
var quizList = [{
question: "What's your favourite Color",
answers: [{
letter: "a",
text: "Dog",
value: "2"
},
// etc
]
},
// etc
];
现在位于顶层quizList
是一个对象数组,每个对象都有一个属性question
和另一个属性answers
,它是一个属性为letter
的对象数组,text
和value
。
答案 3 :(得分:0)
var quizList={
"questions":[
{
"question": "What's your favourite Color",
"answers": {
"a":{
"text":"Blue",
"point":"2"
},
"b":{
"text":"Green",
"point":"4"
},
"c":{
"text":"Red",
"point":"6"
}
"d":{
"text":"Orange",
"point":"8"
}
}
},
{
"question": "What's your favourite Animal",
"answers": {
"a":{
"text":"Dog",
"point":"2"
},
"b":{
"text":"Cat",
"point":"4"
},
"c":{
"text":"Monkey",
"point":"6"
}
"d":{
"text":"Donkey",
"point":"8"
}
}
}
]
};
以json格式试试。