如何解析和求和逗号分隔的数字串

时间:2017-09-04 13:26:28

标签: javascript angularjs json

我从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中的元素时遇到了问题。

感谢您的帮助

1 个答案:

答案 0 :(得分: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);
}
}]);