我有一個數組 - $scope.question = [];
用來存儲從網上API獲取數據:ID,問題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:更多的數據 功能控制器($範圍,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 tryed 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++;
}
});
在我看來,我們需要更多細節來解決這個問題。你能分享更多的代碼表明你附加的每個部分在哪裏? 並顯示數據的格式。 這可以幫助人們來幫助你。 – Neil
@Neil Ofcouse,已經更新了 – Vitaliy
對不起,我真的不明白你的代碼,你想做什麼。你想比較兩個數組嗎? – Neil