2015-10-23 68 views
0

我有一個數組 - $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++; 
        } 

       }); 
+2

在我看來,我們需要更多細節來解決這個問題。你能分享更多的代碼表明你附加的每個部分在哪裏? 並顯示數據的格式。 這可以幫助人們來幫助你。 – Neil

+0

@Neil Ofcouse,已經更新了 – Vitaliy

+0

對不起,我真的不明白你的代碼,你想做什麼。你想比較兩個數組嗎? – Neil

回答

0

可以比較兩個陣列是這樣的:

$scope.name.Xarray[i] == $scope.name.Yarray[n],其中i是在陣列的數目的位置。

然後你必須知道你有迭代這兩個數組。您可以使用forwhile循環。例如:

for (n in $scope.Xarray.lenght) { 
    for (i in $scope.Yarray.lenght) { 
     Xarray[n] == Yarray[i] 
    } 
    } 

這僅僅是一個例子,並不意味着完全是這樣,但是你繼續這些信息。

+0

我試過這樣做,它沒有幫助我。我已更新此主題 – Vitaliy