2017-07-17 31 views
1

所以,我在switch語句中有一段代碼,它幾乎完全在每個case部分重複。對於第一種情況的代碼看起來像如下:我該如何重用一個for循環,其中每次對數組的索引都是不同的

// Some working arrays being defined in each case 
countArr = createArrWithZeroes(height); 
processArr = createEmpty2DArr(width, height); 

for (j = 0; j < height; j++) { 
    for (k = 0; k < width; k++) { 
     item = arr[j][k]; 
     if (item !== null) { 
      // Accessing the working arrays, note the indexing 
      processArr[j][countArr[j]] = item; 
      countArr[j]++; 
     } 
    } 
} 

而且在未來的情況下,我有:

countArr = createArrWithZeroes(width); 
processArr = createEmpty2DArr(width, height); 

for (j = 0; j < height; j++) { 
    for (k = 0; k < width; k++) { 
     item = arr[j][k]; 
     if (item !== null) { 
      processArr[countArr[k]][k] = item; 
      countArr[k]++; 
     } 
    } 
} 

等等,每個情況下,具有不同的索引兩大內線被用於循環。請注意,countArr在兩者之間的定義也不相同。

我覺得這個代碼塊可以被抽象,以便它可以被重用,但我不知道該怎麼做。我可以在for塊中移動switch語句,但問題是countArr數組也需要針對每種情況進行不同的定義。那麼我最終會得到兩個switch語句,其中一個是for循環中的兩個(看起來不太好)。有沒有辦法用高階函數解決這個問題?

+0

請標記語言 – Carcigenicate

+0

這是一個開關的情況下,只有2個選項? – SDhaliwal

+0

不,有4個選項。 countArr數組交替如何初始化(使用寬度或高度),但索引因每種情況而不同。在第三和第四種情況下,我在索引中做了一些基本的算術。 – CJNaude

回答

0

您可以將循環代碼封裝在函數中。編寫它,以便它可以接受回調函數;此回調將允許您傳入不同的代碼段,例如

// First callback- This has the code found in your first nested for statement 
var itemFunctionOne = function(processArr,index,countArr,item) { 
processArr[index][countArr[index]] = item; 
}; 

// Second callback- This has the code found in your second nested for statement 
var itemFunctionTwo = function(processArr,index,countArr,item) { 
processArr[countArr[index]][index] = item; 
}; 

// Encapsulate your looping code in a function. Write it so that it can accept a callback function. 
var itemProcessor = function(itemFunction) { 
countArr = createArrWithZeroes(height); 
processArr = createEmpty2DArr(width, height); 

for (j = 0; j < height; j++) { 
    for (k = 0; k < width; k++) { 
     item = arr[j][k]; 
     if (item !== null) { 
      // Accessing the working arrays, note the indexing 
      itemFunction(); 
      countArr[j]++; 
     } 
    } 
} 
} 

// You could then call this in your switch statement 
itemProcessor(itemFunctionOne) 

// ...and this 
itemProcessor(itemFunctionTwo) 

因爲JavaScript中的對象(以及數組)因引用而傳遞,所以回調函數將按預期工作。

請注意,我還沒有測試過上面的代碼!

我寫行動中這種模式的一個非常簡單的例子here

+1

感謝您花時間回答;酷解決方案! – CJNaude

相關問題