我对 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
,对象2的intTime = 2
,object3是intTime = 3
的intSum
应该是6
。然而,我从IntSum
目前得到的是123
.
任何帮助将不胜感激!
尝试:
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 = [];
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句