javascript – 如果行和列中的四个元素相同,如何检入二维数组?

我正在尝试获得一个嵌套的forEach循环,它在二维数组中找到一对四.

这是一个我的数组的示例:

[0, 0, 0, 0, 0],
[0, 2, 0, 0, 0],
[0, 1, 2, 0, 0],
[0, 1, 2, 2, 0],
[1, 2, 1, 1, 2],

它应该忽略0并且只能找到具有’1’或’2’的四个条目的水平,垂直和对角线对.

有人有什么建议吗?

最佳答案 Jonas的答案比这个更好,但如果你不理解他的语法,这里有一个简化的,更详细的版本:

var field = [
  [0, 0, 0, 0, 0],
  [0, 2, 0, 0, 0],
  [0, 1, 2, 0, 0],
  [0, 1, 2, 2, 0],
  [1, 2, 1, 1, 2]
];

function checkVertical(field, player){
  for(i = 0; i < 5; ++i){
    if (field[0][i] === player 
        && field[1][i] === player
        && field[2][i] === player
        && field[3][i] === player
    ) return true;
    
    if (field[1][i] === player 
        && field[2][i] === player
        && field[3][i] === player
        && field[4][i] === player
    ) return true;
  }
  return false;
}

function checkHorizontal(field, player){
  for(i = 0; i < 5; ++i){
    if (field[i][0] === player 
        && field[i][1] === player
        && field[i][2] === player
        && field[i][3] === player
    ) return true;
    
    if (field[i][1] === player 
        && field[i][2] === player
        && field[i][3] === player
        && field[i][4] === player
    ) return true;
  }
  return false;
}

function checkDiagonal1(field, player){
  // exercise for the reader
  return false;
}

function checkDiagonal2(field, player){
  // exercise for the reader
  return false;
}

function isWin(field, player){
  return checkVertical(field, player) 
    || checkHorizontal(field, player)
    || checkDiagonal1(field, player)
    || checkDiagonal2(field, player);
 
}

console.log(isWin(field, 1));
点赞