2014-10-27 21 views
0

所以我們的目標是要具備以下條件:遞增和重複數在Java腳本一個增量循環3次

k_1_1 
k_1_2 
k_1_3 

k_2_4 
k_2_5 
k_2_6 

k_3_7 
and so on 

我至今是:

但我認爲我的方式關....

while (var qi = 0; qi <= 9; qi++) { 
    for(var ai = 0; ai <= 3; ai++) { 
    var thisName = "k_" + ai + "_" + qi; 
    var thisValue = ""; 
    localStorage.setItem(thisName, thisValue); 
    } 
} 

任何幫助將被apreciated。

謝謝

+1

更改外'while'到'for',啓動'qi'和'ai'在1而不是0。http://jsfiddle.net/6xuj402n/ – 2014-10-27 19:24:48

回答

1

無需兩個迴路,如果你用一點點巧思:

for (var i = 0; i <= 9; i++) { 

    var thisName = "k_" + (Math.floor(i/3)+1) + "_" + (i+1); 

    var thisValue = ""; 
    localStorage.setItem(thisName, thisValue); 
} 
0

您正在使用While循環與For循環參數。 while循環保持循環條件爲TRUE。爲什麼不切換到For循環像這樣(另外,你的氣血和AI切換):

for(var qi = 1; qi <= 9; qi++) { 
for(var ai = 1; ai <= 3; ai++) { 
    var thisName = "k_" + qi + "_" + ai; 
    var thisValue = ""; 
    localStorage.setItem(thisName, thisValue); 
} 
} 
0

另一種解決方案:

for (var ai = 1; ai <= (27) ; ai++) { // 27 was picked arbitrarily (3 * 9) 
             // set to what ever upper limit you need 

    // the ceiling of the current ai number divided by 3 will give you your qi 
    var qi = Math.ceil((ai/3)); 

    //setting your values 
    var thisName = "k_" + qi + "_" + ai; 
    var thisValue = ""; 

    //reporting 
    console.log(thisName, thisValue); 
}