2017-07-17 65 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

相关问题