在循环中连接变量?

时间:2014-12-29 17:01:39

标签: javascript loops variables concatenation

我正在使用AJAX返回并根据用户输入的表单变量显示每月费率。我想循环使用这几个月,而不是重复变量12次。

当前功能代码:

if(data.Jan)
    document.getElementById("Jan").value=data.Jan;
if(data.JanCurrentRate)
    document.getElementById("JanCurrent").innerHTML='$' + data.JanCurrentRate;
if(data.JanProposedRate)
    document.getElementById("JanProposed").innerHTML='$' + data.JanProposedRate;
if(data.JanDifference)
    document.getElementById("JanDifference").innerHTML='$' + data.JanDifference;

if(data.Feb)
    document.getElementById("Feb").value=data.Feb;
if(data.FebCurrentRate)
    document.getElementById("FebCurrent").innerHTML='$' + data.FebCurrentRate;
if(data.FebProposedRate)
    document.getElementById("FebProposed").innerHTML='$' + data.FebProposedRate;
if(data.FebDifference)
    document.getElementById("FebDifference").innerHTML='$' + data.FebDifference;

我想像这样循环:

var MonthArray = ["Jan14","Feb14"];
for (var i = 0; i < MonthArray.length; i++) {
    var month = MonthArray[i];
    if(data.month)
        document.getElementById(month.value=data.month);
    if(data.JanCurrentRate)
        document.getElementById(month+"Current").innerHTML='$' + data.JanCurrentRate;
    if(data.JanProposedRate)
        document.getElementById(month+"Proposed").innerHTML='$' + data.JanProposedRate;
    if(data.JanDifference)
        document.getElementById(month+"Difference").innerHTML='$' + data.JanDifference;
}

我的问题是:我如何制作&#34; data.JanCurrentRate&#34;进入&#34; data.LOOPED_MONTHCurrentRate&#34;每个月?

1 个答案:

答案 0 :(得分:0)

感谢Niet the Dark Absol,我已经解决了这个问题。这是功能循环:

var MonthArray = ["Jan","Feb"];
for (var i = 0; i < MonthArray.length; i++) 
{
    var month = MonthArray[i];
    if(data[month])
        document.getElementById(month).value=data[month];
    if(data[month+"CurrentRate"])
        document.getElementById(month+"Current").innerHTML='$' + data[month+"CurrentRate"];
    if(data[month+"ProposedRate"])
        document.getElementById(month+"Proposed").innerHTML='$' + data[month+"ProposedRate"];
    if(data[month+"Difference"])
        document.getElementById(month+"Difference").innerHTML='$' + data[month+"Difference"];
}