gpt4 book ai didi

javascript - 求和对象数组 Angular 中的属性

转载 作者:行者123 更新时间:2023-11-30 15:16:15 25 4
gpt4 key购买 nike

我对 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 属性求和。因此,如果对象 1 的 intTime = 1、对象 2 的 intTime = 2、对象 3 的 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 = [];

关于javascript - 求和对象数组 Angular 中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44426007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com