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

标签 javascript angularjs json

我在从 JSON 读取数据时遇到问题。

这是我的 Controller :

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

感谢您的帮助

最佳答案

试试这个:

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);
}
}]);

关于javascript - 如何解析和求和逗号分隔的数字字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46038124/

相关文章:

javascript - 路由在 AngularJS 应用程序中不起作用

java - Spring 安全 AngularJS 禁止 403

javascript - 对 Paypal 的 HTTP 请求

javascript - AngularJS:即使它们显示正确,为什么我会得到 NaN?

javascript - HTML5 promise : does resolve call end promise

javascript - 将变量传递给数组列表

Javascript - 如何在使用 iframe、使用 dom 而不是 jquery 时更改页面内的元素内容

jQuery 产品数组

php - JSON 解析 --> Swift | JSON 写入中的顶级类型无效

java - 如何在Spring Controller 中使用JSON发送继承的对象?