我试图找出如何检查二维数组是否连续包含 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)。
我希望我已经解释清楚了。谢谢你的建议。
胡说叔叔
相关分类