2014-01-23 60 views
1

我必須獲取最近幾周基於每週的一些記錄,並且必須將一週記錄中的值添加到數組中。所以,我宣佈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)); 
} 

如何將內循環的值添加到基於外循環的數組?

+0

您不能按名稱訪問變量。你爲什麼不使用二維數組? – Barmar

+0

'[arr_name]'不是對名稱在'arr_name'中的數組的引用。它是一個包含'arr_name'中的字符串的數組。 – Barmar

+0

'[「string」]'創建一個包含「string」的數組。如果我們改變你的代碼,改爲使用'var a = [「string」]; a.push(「val」);'我們最終會用'[「string」,「val」]''。這就是你的代碼目前所做的;它會創建一個包含字符串的數組(它等於數組變量的名稱),它不會被分配給任何變量本身,然後將'val1'推入其中。 –

回答

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)); 
} 
+0

你需要在合計循環之前將'myTotal'設置爲0。 – Barmar

0

如果要動態操控全局變量,你可以使用窗口前綴:

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

你只能用全局變量來做,而不能用局部變量。 – Barmar

+0

對於本地,您可以創建包含所有數組的對象,並使用該對象而不是窗口前綴..就像var store = {}; store.w_1 = [];等。 –

相關問題