我有一个数组 - $scope.question = [];
,用于存储从网络API获取的数据:id,question和correctAnswer
quizService.getQuestions(id).success(function (data) {
$scope.question = data;
});
而且,我还有另一个数组,用户回答问题:
$scope.binding = {
answers: {}
};
$scope.setAnswer = function (answer, id) {
$scope.binding.answers[id] = answer;
};
问题是,如何从数组中获取数据并进行比较?
$scope.question[id]
$scope.question[correctAnswer]
这是正确的实现吗?
if ($scope.binding.answers[id] == $scope.question[id] && $scope.binding.answer[answer] == $scope.question[correctAnswer]) {
...
}
P.S。我是angularjs的新手。
更新1:更多数据 函数控制器($ scope,quizService){
$scope.currentAnswer = null;
//Set the answer from radio buttons
$scope.setAnswer = function (answer, id) {
$scope.binding.answers[id] = answer;
};
$scope.question = [];
$scope.binding = {
answers: {}
};
updQuestion();
function updQuestion() {
var id = 1;
//Get the question
quizService.getQuestions(id).success(function (data) {
$scope.question = data;
});
//Button to get next question
$scope.nextQuestion = function () {
id++;
quizService.getQuestions(id).success(function (data) {
$scope.question = data;
$scope.currentAnswer = $scope.binding.answers[id];
});
};
//Submit button when user passed all questions
$scope.onSubmit = function () {
quizService.postResult().sucess(function () {
for (var i = 0; i < $scope.question.length; i++) {
if ($scope.binding.answers[id] == $scope.question[id] && $scope.binding.answer[answer] == $scope.question[correctAnswer]) {
numbOfCorrectAnswers++;
}
$scope.question.push(numbOfCorrectAnswers);
}
});
};
更新2
所以,我尝试使用2 for for循环和forEach,无论如何都无法从数组中的对象中获取值。
$scope.onSubmit = function () {
var numbOfCorrectAnswers = 0;
var answers = null;
var n = 0;
var b = 0;
var questions;
for (n = 0; n < $scope.getQuestions.lenght; n++) {
for (b = 0; b < $scope.binding.answers.lenght; b++) {
var questions = $scope.getQuestions[n];
var getAnswer = $scope.binding.answer[n];
if (questions.Id == getAnswer.id && questions.CorrectAnswer == getAnswer.answer) {
numbOfCorrectAnswers++;
}
});
答案 0 :(得分:0)
您可以像这样比较两个数组:
$scope.name.Xarray[i] == $scope.name.Yarray[n]
,其中i
是数组中的数字。
然后你必须知道你有两个数组的迭代。您可以使用for
或while
循环。例如:
for ( n in $scope.Xarray.lenght ) {
for ( i in $scope.Yarray.lenght ) {
Xarray[n] == Yarray[i]
}
}
这只是一个例子,并不意味着就是这样,但你继续这些信息。