我正在尝试制作一个对象,其中的关键是年数,价值是金额

vm.argiterraYearlyLocalCost = {"2016":0,"2017":0,"2018":0,"2019":0} //year(key):amount(value)


我在视图中有一个输入字段,可让我输入新的金额,每次添加不同的addLocalCostContributor时,它都会检查条件是否匹配,该金额将添加到年份中。

function addLocalCostContributor(localCost, year) {
        localCost.contributors.push({});

          for(var i=0; i < localCost.contributors.length;i++ ) {
            if(angular.isDefined(localCost.contributors[i].contributor) && localCost.contributors[i].contributor.name ==='Agriterra') {
              var amount = parseInt(localCost.contributors[i].amount);
              vm.argiterraYearlyLocalCost[year] = parseInt(vm.argiterraYearlyLocalCost[year] || 0) + amount;
            }
          }
    }

vm.argiterraYearlyLocalCost = {};//ths is intiliased in the top of angular controller


问题在于,每当添加新的金额并满足条件时,金额都会增加,但会重新开始循环。例如,我添加firstAmount,它给了我{'2016':firstAmount},但是当我添加newAmount并提交时,它再次开始循环,它给出了{'2016':firstAmount + firstAmount + newAmount},而我想要的只是firstAmount + newAmount。如果我每次提交时都可以重置vm.argiterraYearlyLocalCost[year](并且该函数循环以增加属性),我将得到正确的答案。
javascript - javascript:再次遍历数组时,我想重置对象属性-LMLPHP
如果有人可以从不同的角度看到,我无法清楚地思考如何以及在何处重置此属性。

最佳答案

尝试在for循环运行之前重设该年份的金额。

function addLocalCostContributor(localCost, year) {
    localCost.contributors.push({});

    vm.argiterraYearlyLocalCost[year] = 0; // <= added this line

    for (var i = 0; i < localCost.contributors.length; i++) {
        if (angular.isDefined(localCost.contributors[i].contributor)
        && localCost.contributors[i].contributor.name === 'Agriterra') {
            var amount = parseInt(localCost.contributors[i].amount);
            vm.argiterraYearlyLocalCost[year] = parseInt(vm.argiterraYearlyLocalCost[year] || 0) + amount;
        }
    }
}

vm.argiterraYearlyLocalCost = {};

09-11 00:06