我在显示的测验中有很多问题。所有值都来自json对象,结构为:
sections: [
subSections:[
"questions":[
"title":"a",
"number":"b",
"name":"c",
"answers":[
{
"answerKey": "true",
"answerLabel": "true"
},
{
"answerKey": "false",
"answerLabel": "false"
}
]
]
]
]
我想要完成的是在先前编写的函数中从数组中获取这些值:
function getRandomFiveQuestions(questionArray){
var returnArray = [];
var loopLength;
loopLength = questionArray.length >= 5 ? 5 : questionArray.length;
outerLoop:
for(i=0; i<loopLength; i++){//do this 5 times
var randomIndex = Math.round(Math.random() * questionArray.length); //get a random whole number between 0 and the array length
if(returnArray.length != 0){ //if the list of questions we're compiling already has items
for(j=0; j<returnArray.length; j++){//loop through the return array
if(returnArray[j]==questionArray[randomIndex]){ //if the random item is already in the return array
i--; //redo this step in the outer loop, which will get a new random number and try again
continue outerLoop; //skip everything else in the outer loop
}
}
//if we've gotten to the end of the inner loop and a duplicate wasn't found, we'll run this code
//which will add the random item to the return array
returnArray.push(questionArray[randomIndex]);
}
else{ //if there are no items in the return array yet
//add the item to the return array
returnArray.push(questionArray[randomIndex]);
}
//console.log(returnArray[i]);
}
//when we're done looping, return the resulting array
return returnArray;
};
然后提交比较答案,以便如果其中任何一个为真,那么真正的组合将以%显示得分。
要选择的选项显示在单选按钮中。
我很想知道如何用JS实现这一目标。我已经获得了很多帮助,以前的功能,抓住一个数组,现在我只考虑一般概念,并不能真正提出任何可靠的东西。仍然学习JS。
答案 0 :(得分:1)
我的方法,因为我不太确定设置(我可能只是累了):
angular.module('quizApp', []);
angular.module('quizApp').controller('QuizCtrl',
function() {
var ctrl = this;
this.selectedAnswers = {};
this.questions = [{
'title': 'Question 1 ?',
'answers': [{
'title': 'Answer 1',
'correct': false,
}, {
'title': 'Answer 2',
'correct': true,
}]
}, {
'title': 'Question 2 ?',
'answers': [{
'title': 'Answer 1',
'correct': false,
}, {
'title': 'Answer 2',
'correct': true,
}]
}]
this.validate = function() {
ctrl.correctAnswers = 0;
ctrl.totalQuestions = ctrl.questions.length;
for (var answer in ctrl.selectedAnswers) {
answerObj = ctrl.selectedAnswers[answer]
if (answerObj.correct) {
ctrl.correctAnswers += 1;
}
}
}
})
<div ng-app='quizApp' ng-controller='QuizCtrl as qCtrl'>
<div ng-repeat='question in qCtrl.questions'>
<p>{{ question.title }}</p>
<div ng-repeat='answer in question.answers'>
<input type='radio' name='{{question.title}}' ng-model='qCtrl.selectedAnswers[question.title]' ng-value='answer'>{{ answer.title }}
</div>
</div>
<br>
<button ng-click='qCtrl.validate()'>Validate answers</button>
<p ng-if='qCtrl.totalQuestions'>
{{ qCtrl.correctAnswers }}/{{ qCtrl.totalQuestions }} were correct
</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>