如何检查二维数组是否连续具有三个相同的值

我试图找出如何检查二维数组是否连续包含 3 个相同的值。此二维数组将由用户生成,因此用于检查的函数必须是动态的。


例如,假设用户输入 4x4。结果会是这样


  let arr=[

    [" "," "," "," "],

    [" "," "," "," "],

    [" "," "," "," "],

    [" "," "," "," "]

  ]

让我向该数组添加一些值


  let arr=[

    [" "," ","x","x"],

    ["x","x","x"," "],

    [" "," "," "," "],

    [" "," "," "," "]

  ]

我试图用这个函数来解决这个问题,但昨天我注意到它不适合。


  function checkArray(arr){

    for(let i=0;i<arr.length;i++){

      let count = 0;

      for(let j=0;j<arr[i].length;j++){

        if(arr[i][j] === 'x'){

          count++;

        }


        if(count === 3 ){

          console.log('x wins')

        }

      }

    }

  }

  

  console.log(checkArray(arr)) //count will be 3 and console.logs 'x wins'.

此时此刻,我认为一切正常,直到我尝试像这样填充数组。如您所见,没有连续三个 X(我的意思是它们不是这样的 - x,x,x),它们之间有一个空格。


  let arr=[

    [" "," ","x","x"],

    ["x","x"," ","x"],

    [" "," "," "," "],

    [" "," "," "," "]

  ]

所以不应该满足条件并且函数不应该是 console.log('w wins')。但确实如此。我解决这个问题的方法适用于整行,而不仅仅是连续 3 个 (x,x,x)。


我希望我已经解释清楚了。谢谢你的建议。


HUH函数
浏览 172回答 1
1回答

胡说叔叔

如果您没有获得 . ,则需要重置计数'x'。function checkArray(arr) {&nbsp; for (let i = 0; i < arr.length; i++) {&nbsp; &nbsp; let count = 0;&nbsp; &nbsp; for (let j = 0; j < arr[i].length; j++) {&nbsp; &nbsp; &nbsp; if (arr[i][j] === 'x') {&nbsp; &nbsp; &nbsp; &nbsp; count++;&nbsp; &nbsp; &nbsp; &nbsp; if (count === 3) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // place check after incrementing&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log('x wins')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; count = 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // reset&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }&nbsp; return false;}let arr = [&nbsp; [" ", " ", "x", "x"],&nbsp; ["x", "x", " ", "x"],&nbsp; [" ", " ", " ", " "],&nbsp; [" ", " ", " ", " "]]console.log(checkArray(arr));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript