我对Angular和Javascript相当新,所以需要一些指导。我想要计算对象数组中值的总和和平均值。通过输入框将对象推入数组,到目前为止,这是我的代码:
var myApp = angular.module("myApp", []);
myApp.controller("myController", function($scope){
$scope.newLog = {};
$scope.logs = [
{project: "",
phase: "",
date: "",
startTime: "",
intTime: "",
endTime: "",
comments: ""}
];
$scope.saveLog = function(){
//CREATING DELTA TIME
var newTimeLog = $scope.newLog;
var begin = (newTimeLog.startTime).getTime();
var end = (newTimeLog.endTime).getTime();
var i = newTimeLog.intTime;
var ii = parseInt(i);
var intMilisec = ii*60000;
if( isNaN(begin) )
{
return "";
}
if (begin < end) {
var milisecDiff = end - begin;
}else{
var milisecDiff = begin - end;
}
var minusInt = milisecDiff - intMilisec;
var milisec = parseInt((minusInt%1000)/100)
, seconds = parseInt((minusInt/1000)%60)
, minutes = parseInt((minusInt/(1000*60))%60)
, hours = parseInt((minusInt/(1000*60*60))%24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
var deltaFormat = hours + " Hours " + minutes + " Minutes";
newTimeLog["deltaTime"] = deltaFormat;
$scope.logs.push($scope.newLog);
$scope.newLog = {};
};
$scope.intSum = function(){
var sum = 0;
for (var i = 0; i < $scope.logs.length; i++){
sum += $scope.logs[i].intTime;
}
return sum;
};
});
所以intSum
函数是我遇到问题的地方 - 我想要总结所有对象的intTime
属性。因此,如果object1的intTime = 1
,object2的intTime = 2
,object3的intTime = 3
intSum
应为6
。但是,我目前从IntSum
获得的是123
。
非常感谢任何帮助!
答案 0 :(得分:2)
尝试:
sum += parseInt($scope.logs[i].intTime);
而不是:
sum += $scope.logs[i].intTime;
编辑:我建议你看看reduce函数,这是在这种情况下循环你的数组的javascript方法:
https://www.w3schools.com/jsref/jsref_reduce.asp
EDIT2:您将$scope.logs.intTime
初始化为""
。第一个值保留在数组中并生成NaN
。
我建议你像这样初始化你的数组:
$scope.logs = [];
答案 1 :(得分:0)
intTime在您的对象中定义为String。所以当你在做总和时,它实际上正在进行字符串连接。使用pasrseInt转换为Number并执行求和。
答案 2 :(得分:0)
在求和+ =:
时尝试使用parseInt$scope.intSum = function(){
var sum = 0;
for (var i = 0; i < $scope.logs.length; i++){
sum += parseInt($scope.logs[i].intTime);
}
return sum;
};
答案 3 :(得分:0)
intTime
类型的string
转换为int
您可以使用JavaScript reduce()函数
arr.reduce(callback, [initialValue])
callback = function(accumulator, currentValue) { return accumulator + currentValue } //accumulator is the currentSum since the last callback
示例:http://jsfiddle.net/GruffBunny/4cFU3/
您的sum函数可写为:
$scope.sum = function(items, prop){ //items is the array, prop is the property you want to its value to be calculated
return items.reduce( function(a, b){
return a + parseInt(b[prop]); //in the first attempt, a=0 which is the same as initialValue
}, 0); //initially sum=0, so initialValue is 0
};
$scope.sum($scope.logs, 'iniTime')
参考文献: