gpt4 book ai didi

javascript:再次循环数组时,我希望重置对象属性

转载 作者:行者123 更新时间:2023-12-02 14:54:24 26 4
gpt4 key购买 nike

我正在尝试制作一个对象,其中键是年份,值(value)是金额

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

我在 View 中有一个输入字段,它可以让我创建新的金额,每次我添加不同的 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 +新金额。如果我可以在每次提交时重置 vm.argiterraYearlyLocalCost[year] (并且函数循环增加属性),我将得到正确的答案。 looping problem when logged如果有人可以用不同的眼睛看到的话,我无法清楚地思考如何以及在哪里重置此属性。

最佳答案

尝试在 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 = {};

关于javascript:再次循环数组时,我希望重置对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35937727/

26 4 0
文章推荐: javascript - 使用 javascript 将类添加到除
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com