如何重用每次对数组进行不同索引的 for 循环

How do I reuse a for-loop where an array is indexed differently each time

所以,我在 switch 语句中有一段代码,几乎在每个 case 部分都完全重复。第一种情况的代码如下所示:

// 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]++;
        }
    }
}

依此类推,每个案例在两个 for 循环中使用不同的索引。请注意,countArr 在两者之间的定义也不同。

我觉得这块代码可以抽象出来重用,但我不知道该怎么做。我可以在 for 块内移动 switch 语句,但问题是 countArr 数组也需要针对每种情况进行不同的定义。那么我最终会得到两个 switch 语句,其中一个在两个 for 循环中(看起来不太好)。有没有办法用高阶函数解决这个问题?

您可以将循环代码封装在一个函数中。编写它以便它可以接受回调函数;此回调将允许您传入不同的代码段,例如

// 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