【问题标题】:How do I reuse a for-loop where an array is indexed differently each time如何重用一个 for 循环,其中每次索引数组的方式都不同
【发布时间】:2017-07-17 15:11:09
【问题描述】:

所以,我在 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 循环内(看起来不太好)。有没有办法用高阶函数解决这个问题?

【问题讨论】:

  • 请标记语言
  • 这是一个只有 2 个选项的开关盒吗?
  • 不,有 4 个选项。 countArr 数组的初始化方式会交替变化(使用宽度或高度),但每种情况的索引不同。在第 3 和第 4 种情况下,我在索引中做了一些基本的算术运算。

标签: javascript loops reusability higher-order-functions


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 2023-03-31
    • 2016-11-08
    • 2013-04-03
    • 1970-01-01
    • 2016-08-26
    相关资源
    最近更新 更多