2016-04-13 73 views
-1

有沒有辦法循環這段代碼並改變數字(i = 1,2,3)以避免重複?javascript改變字符串中的數字

if (bool) { 
    reeks1Getallen = reeks1.splice(0, k1 % (reeks1.length)); 
    reeks2Getallen = reeks2.splice(0, k2 % (reeks2.length)); 
    reeks3Getallen = reeks3.splice(0, k3 % (reeks3.length)); 
} else { 
    reeks1Getallen = reeks1.splice(0, (reeks1.length) - k1 % reeks1.length); 
    reeks2Getallen = reeks2.splice(0, (reeks2.length) - k2 % reeks2.length); 
    reeks3Getallen = reeks3.splice(0, (reeks3.length) - k3 % reeks3.length); 
} 
reeks1 = reeks1.concat(reeks1Getallen); 
reeks2 = reeks2.concat(reeks2Getallen); 
reeks3 = reeks3.concat(reeks3Getallen); 
+3

不要使用不同的變量名稱。使用數組var'reeks = [...]' – Bergi

+0

每個語句中有3個字符串變化,我不會避免與1個單個數組重複,對嗎? @Bergi –

+1

我在這些語句中沒有看到任何字符串? – Bergi

回答

2

收聽@Bergi必須說的話;這看起來就像我的教授計劃之一。如果你要循環使用索引

for (let [reeks, k] of [[reeks1, k1], [reeks2, k2], [reeks3, k3]]) { 
    const getallen = reeks.splice(0, bool ? k % reeks.length : reeks.length - k % reeks.length); 
    reeks = reeks.concat(getallen); 
} 
1

,您應該使用對象的數組:

如果你不能得到馬上擺脫你的枚舉變量,你的代碼應該是等同於。這個答案比其他人更詳細些,但它也應該完成這項工作:

var objList = [ 
    { 
    reeks: [], // fill with your own array 
    reeksGetallen: [], // fill with your own array 
    k: 1 
    }, 
    { 
    reeks: [], // fill with your own array 
    reeksGetallen: [], // fill with your own array 
    k: 2 
    }, 
    { 
    reeks: [], // fill with your own array 
    reeksGetallen: [], // fill with your own array 
    k: 3 
    } 
]; 

for (var i = 0; i < objList.length; i++) { 
    var reeksGetallen = objList[i].reeksGetallen; 
    var reeks = objList[i].reeks; 
    var k = objList[i].k; 

    if (bool) { 
    reeksGetallen = reeks.splice(0, k % reeks.length); 
    } else { 
    reeksGetallen = reeks.splice(0, reeks.length - k % reeks.length); 
    } 

    reeks = reeks.concat(reeksGetallen); 
}