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

标签 javascript angularjs arrays object

我对 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/

相关文章:

javascript - 从 redux 中删除数据并保存滚动位置

javascript - 反转 ng-repeat 顺序,迭代 Angel Fire 数组

javascript - 带有 codeigniter 的 ui-router 在刷新页面或使用 html5mode(true) 粘贴 URL 时给出 404

arrays - 数组无法正确排序 : Swift 4

python - [ :, :] 在 NumPy 数组上是什么意思

javascript - ionic 运行 android 不工作

javascript - php服务器无法使用$.http().post请求从angularjs接收json变量

javascript - 不确定如何在单击 div 外部时隐藏 div

java - Java 中 toCharArray() 和 toString() 的运行时间是多少?

javascript - CSS 或 JavaScript 如何对 Azure B2C 电子邮件验证过程的不同步骤使用react?