如何解析和求和以逗号分隔的字符串
问题描述:
我从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中的元素时遇到问题。
感谢您的帮助
答
试试这个:
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);
}
}]);
这哪里是'$ scope.getAvg'功能是打电话?你使用','分隔符测试值,不可能添加。 –
不,不可以添加。 ,getAvg在调用html – mrkibzk
'91,92,93,94,95,96,97'+'101,102,103,104,105,106,107'这是不可能的 –