将循环结果添加到数组并在最后一个循环后显示添加元素的总和

时间:2014-01-23 12:07:00

标签: javascript

我必须在最后几周根据每周的基础获得一些记录,并且必须将一周记录中的值添加到数组中。所以,我宣布了6个数组来存储6周的记录。我的代码是:

var w_0 = [];var w_1 = [];var w_2 = [];var w_3 = [];var w_4 = [];var w_5 = [];
var myTotal = 0;
var arr_name = "";

for(var j=0;j<=5;j++)
{

    var start_date="";
    var end_date="";

    //code to fetch the records added between start_date,end_date
    //there may be more that one record

    var count = getRecordCount(); //My function
    //following loop is to fetch value from a record
    for(var i=0;i<count;i++)    
    {
        var val1 = getRecordByIndex(i).getValue("rem_val"); //getRecordByIndex() and getValue() are our pre-defined functions. 

        //here I want to push the values into the array w_0

        arr_name = "w_"+j;
        [arr_name].push(val1); //this is not working
        alert([arr_name]); //showing 'w_0'

    } 

    //and here I want to sum all the array elements when i reaches its maximum
    for(var a=0;a<[arr_name].length; a++){
        myTotal += parseInt([arr_name][a]);  
    }
    alert("Total value of week"+j+"="+parseInt(myTotal)); 
}

如何基于外循环将内循环的值添加到数组?

2 个答案:

答案 0 :(得分:1)

每当你发现自己创建带有顺序编号名称的变量时,你应该使用数组。

var w = [[], [], [], [], []];

然后,只要您尝试使用[arr_name]引用特定的w_j变量,就应该使用w[j]

for(var j=0;j<=w.length;j++)
{

    var cur_w = w[j];
    var start_date="";
    var end_date="";

    //code to fetch the records added between start_date,end_date
    //there may be more that one record

    var count = getRecordCount(); //My function
    //following loop is to fetch value from a record
    for(var i=0;i<count;i++)    
    {
        var val1 = getRecordByIndex(i).getValue("rem_val"); //getRecordByIndex() and getValue() are our pre-defined functions. 

        cur_w.push(val1);
        alert(cur_w);

    } 

    //and here I want to sum all the array elements when i reaches its maximum
    for(var a=0;a<cur_w.length; a++){
        myTotal += parseInt(cur_w[a]);  
    }
    alert("Total value of week"+j+"="+parseInt(myTotal)); 
}

答案 1 :(得分:0)

如果要动态操作全局变量,可以使用窗口前缀:

arr_name = "w_"+j;
window[arr_name].push(val1); // This should work