2017-09-04 95 views
0

我從JSON讀取我的數據時遇到問題。如何解析和求和以逗號分隔的字符串

這是我的控制器:

myApp.controller("abcdctrl", ['$scope', 'orderByFilter', '$http', function ($scope, orderBy, $http) { 
console.log('abcdctrl'); 
$http.get("http://localhost:8080/api/session") 
    .then(function (response) { 
     $scope.data = response.data.session; 
    }); 

$scope.getAvg = function() { 
    var total = Number("0"); 
    for (var i = 0; i < $scope.data.length; i++) { 
     total += parseInt($scope.data[i].testing); 
    } 
    return parseInt(total/$scope.data.length); 
} 
}]); 

這是我的JSON

{ 
"session": [ 
    { 
     "id": 1, 
     "testing": "91,92,93,94,95,96,97", 
     "playing": "11,12,13,14,15,16,17", 
     "acc_id": 1 
    }, 
    { 
     "id": 2, 
     "testing": "101,102,103,104,105,106,107", 
     "playing": "1,2,3,4,5,6,7", 
     "player_id": 2 
    }, 
    { 
     "id": 3, 
     "testing": "111,112,113,114,115,116,117", 
     "playing": "21,22,23,24,25,26,27", 
     "acc_id": 3 
    } 
] 
} 

我要計算每個球員的平均值品嚐和演奏,我想計算的總平均測試和玩的價值。我成功地打印了整個JSON,但在訪問JSON中的元素時遇到問題。

感謝您的幫助

+0

這哪裏是'$ scope.getAvg'功能是打電話?你使用','分隔符測試值,不可能添加。 –

+0

不,不可以添加。 ,getAvg在調用html – mrkibzk

+0

'91,92,93,94,95,96,97'+'101,102,103,104,105,106,107'這是不可能的 –

回答

1

試試這個:

myApp.controller("abcdctrl", ['$scope', 'orderByFilter', '$http', function ($scope, orderBy, $http) { 
 
console.log('abcdctrl'); 
 
$http.get("http://localhost:8080/api/session") 
 
    .then(function successCallback(response) { 
 
     $scope.data = response.data.session; 
 
    }, function errorCallback(response) { 
 
     // called asynchronously if an error occurs 
 
     // or server returns response with an error status. 
 
}); 
 

 
$scope.getAvg = function() { 
 
    var total = Number("0"); 
 
    for (var i = 0; i < $scope.data.length; i++) { 
 
     var grades = $scope.data[i].testing.split(','); 
 
     for(var j = 0; j < grades.length; j++){ 
 
      total += parseInt(grades[j]); 
 
     } 
 
    } 
 
    return parseInt(total/$scope.data.length); 
 
} 
 
}]);

相關問題