【问题标题】:Matching consecutive values in 2D array匹配二维数组中的连续值
【发布时间】:2026-02-13 23:45:02
【问题描述】:

我试图弄清楚如何在二维数组中找到 3 个或匹配的连续值。我想我已经弄清楚了水平和垂直匹配但是如果相同的值出现在两个不同的行中,如下列表数组(myArray):

| 1 | 2 | 2 | 0 |
| - | 2 | 0 | 1 |
| 1 | - | 0 | 1 |

在这个特定的二维数组中,myArray[0][1]、myArray[0][2] 和 myArray[1][1] 都匹配 2 的值。

这是我必须为水平和垂直匹配找到匹配项的 JavaScript:

for (i in myArray) {
    for (j in myArray[i]) {
        if (myArray[i][j] == myArray[i][j - 1] && myArray[i][j - 1] == myArray[i][j - 2] && myArray[i][j] != "-") {
            // do something
        }
        if (i > 1) {
            if (myArray[i][j] == myArray[i - 1][j] && myArray[i - 1][j] == myArray[i - 2][j] && myArray[i][j] != "-") {
                // do something
            }                           
        }
    }
}

我在正确的轨道上吗?我猜我可以混合这两个 if 语句来找到匹配项,但我对如何找到匹配项有点迷茫。

谢谢!

【问题讨论】:

  • 1.使用三等号 (===) 2. 你到底在问什么?您是否需要判断水平和垂直方向是否匹配?举一个期望输出的例子

标签: javascript arrays multidimensional-array


【解决方案1】:

测试每个元素周围的交叉

for (var y=0, yLen=myArray.length; y<yLen; y++){
  for (var x=0, xLen=myArray[y].length; x<xLen; x++){
      var matches = 0,
          testing = myArray[y][x];
      // test left
      if (x>0 && myArray[y][x-1] === testing) matches++;
      // test right
      if ((x<myArray[y].length-1) && myArray[y][x+1] === testing) matches++; 
      // test above
      if (y>0 && myArray[y-1][x] === testing) matches++; 
      // test below
      if ((y<myArray.length-1) && myArray[y+1][x] === testing) matches++; 

      if (matches>=2){
         console.log(y,x,' is the central or corner element of a 3-or-more group');
      }
  }
}

请记住,这只会对组的中心元素返回 true(3 个水平或 3 个垂直的中心元素,或者组在两个方向上时的角元素


由于Why is using "for...in" with array iteration a bad idea?中描述的原因,将for .. in用于数组也是一个坏主意

【讨论】: