设置说明: 我正在建立一个有旋转器的琐事游戏。该微调器分为6个类别(第6类是所有前5个类别的组合)。前5个类别将拥有它自己的一组问题。一旦微调器停在一个类别上,就会出现一个表格,根据它的类别按顺序提出一系列问题。每个问题有3个选择,其中1个是正确的选择。
下面是一个简短的问题库数组来说明我的想法: ```
var questionBankArray =
[{
category: "Category1",
question: "What does the following expression return? <br> 3 / 'bob';",
choices: ["undefined", "ReferenceError", "NaN"],
correctAnswer: "NaN"
},{
category: "Category1"
question: "What is a method?",
choices: ["Used to describe an object.", "A function assigned to an object.", "Performs a function on one or more operands or variables."],
correctAnswer: "A function assigned to an object."
},{
category: "Category2"
question: "Which company first implemented the JavaScript language?",
choices: ["Netscape Communications Corp.", "Microsoft Corp.", " Sun Microsystems Corp."],
correctAnswer: "Netscape Communications Corp."
},{
category: "Category2"
question: "When was the first release of a browser supporting JavaScript?",
choices: ["1996", "1995", " 1994"],
correctAnswer: "1995"
},
];
```
我想通过问题来讨论对象,并按类别,在该类别中进行随机播放。我还希望能够在该类别的每个问题中改变选择。我该怎么做?将它重写为这样会更容易:
questionBankArray =
[{
CategoryBank1:
[{
question1: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
},{
question2: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
}],
CategoryBank2:
[{
question1: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
},{
question2: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
}]
}];
答案 0 :(得分:2)
我认为理想的结构是这样的:
questionBankArray =
[{
category:"first category",
questions:
[{
question1: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
},{
question2: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
}]
},
{
category: "second category",
questions:
[{
question1: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
},{
question2: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
}]
}];
创建一个随机函数:
function shuffle(o){
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
开始在外部数组上循环并越来越深入,将最内层的shuffle函数应用到外部数组
for (var category in questionBankArray) {
for (var question in category.questions) {
shuffle(question.choices);
}
shuffle(category);
}
shuffle(questionBankArray);