如何缩短此代码? (环)

时间:2016-11-03 20:43:54

标签: javascript loops if-statement

所以,我只想缩短下面的代码:

var start=function(){
var bevetel = document.getElementsByClassName("bevetel");
var yearlyincome2010=0;
var yearlyincome2011=0;
var yearlyincome2012=0;
var yearlyincome2013=0;
var yearlyincome2014=0;
var yearlyincome2015=0;
var yearlyincome2016=0;
for(var i=0; i < bevetel.length; i++) {
    if (i<3) {
        if (bevetel[i].value) {
            yearlyincome2010 += parseInt(bevetel[i].value);
            document.getElementById("yearlyincome2010").innerHTML=yearlyincome2010;
        }
        else {}
    }
    else if (i<7){
        if (bevetel[i].value) {
            yearlyincome2011 += parseInt(bevetel[i].value);
            document.getElementById("yearlyincome2011").innerHTML=yearlyincome2011;
        }
        else {}
    }
    else if (i<11) {
        if (bevetel[i].value) {
            yearlyincome2012 += parseInt(bevetel[i].value);
            document.getElementById("yearlyincome2012").innerHTML=yearlyincome2012;
        }
        else {}
    }
    else if (i<15) {
        if (bevetel[i].value) {
            yearlyincome2013 += parseInt(bevetel[i].value);
            document.getElementById("yearlyincome2013").innerHTML=yearlyincome2013;
        }
        else {}
    }
    else if (i<19) {
        if (bevetel[i].value) {
            yearlyincome2014 += parseInt(bevetel[i].value);
            document.getElementById("yearlyincome2014").innerHTML=yearlyincome2014;
            }
        else {}
    }
    else if (i<23) {
        if (bevetel[i].value) {
            yearlyincome2015 += parseInt(bevetel[i].value);
            document.getElementById("yearlyincome2015").innerHTML=yearlyincome2015;
            }
        else {}
    }
}
};

Theese#annualincome201 $&#39; s是标题的ID ... .bevetel是一个输入类。

此功能计算每个四个输入并分别给出答案。

1 个答案:

答案 0 :(得分:1)

var YearsAndIncomes = {
    yearIncomes = [],
    quarters = [],
}

let year = 2010;
let income = 0;

for (let i = 0; i < bevetel.length; i++) {
    income += bevetel[i];
    if ((i%4) == 3) {
        YearsAndIncomes.yearIncomes.push("YearlyIncome" + year);
        YearsAndIncomes.income = income;
        income = 0;
        year += 1;
    }
}

for (let i = 0; i < YearsAndIncomes.yearIncomes.length; i++) {
    document.getElementById(YearsAndIncomes.yearIncomes[i]).innerHTML = YearsAndIncomes.income[i];
}

这样可以更轻松地抽象出您的工作。循环的基本规则。不要硬编码你将要添加的更多东西(如年)。尝试并做一次重复的事情(即document.getElementById)。这是多次执行的,但只存在于一个地方,因此如果需要修复或更改,您始终知道要去哪里。

另外,使用&#39; for(让我而不是&#39; for(var i&#39;。Var每次都会创建一个全局变量,你不想在迭代器上这样做) &#39; i&#39;。让一个变量在你离开闭包后消失,即让我只在for循环中存在。