React数独校验出现TypeError: Cannot read property '0' of undefined问题排查
解决数独棋盘校验的TypeError和逻辑问题
让我们一步步拆解并修复你的代码问题:
1. 触发TypeError的核心原因
在boardIsValid方法的内层循环里,你不小心把循环增量写错了:
for (let j = 0; j < currentBoard[0].length; i++) {
这里本该写j++,结果写成了i++——这会导致i在每次内层循环时疯狂递增,很快就超出了棋盘的行数(你的棋盘只有9行)。当i >= 9时,currentBoard[i]就变成了undefined,再去访问currentBoard[i][j]自然就会抛出TypeError: Cannot read property '0' of undefined。
修复后的内层循环:
for (let j = 0; j < currentBoard[0].length; j++) {
2. 数组引用比较的逻辑错误
在boxIsValid方法中,你用[i, j] !== position判断是否为当前单元格,但数组是引用类型,哪怕两个数组元素完全相同,直接比较也会返回false(比如[1,2] !== [1,2]结果是true,因为它们指向不同内存地址)。
修复这个判断逻辑:
if (this.state.board[i][j] === num && !(i === position[0] && j === position[1])) { return false; }
3. 额外的棋盘维度小提示(可选)
注意到你的this.state.board是9行,但每行有10个元素(索引0-9),而标准数独是9x9的。如果这是笔误,建议调整为每行9个元素,避免后续逻辑出现不必要的边界问题。
修复后的完整代码
boardIsValid() { const currentBoard = this.state.board; for (let i = 0; i < currentBoard.length; i++) { for (let j = 0; j < currentBoard[0].length; j++) { // 修复循环增量错误 // 排除空白单元格(0)的校验 if (currentBoard[i][j] !== 0 && !this.positionIsValid(currentBoard[i][j], [i, j])) { return false; } } } return true; } positionIsValid(num, position) { return this.rowIsValid(num, position) && this.columnIsValid(num, position) && this.boxIsValid(num, position); } rowIsValid(num, position) { for (let i = 0; i < this.state.board[0].length; i++) { if (this.state.board[position[0]][i] === num && position[1] !== i) { return false; } } return true; } columnIsValid(num, position) { for (let i = 0; i < this.state.board.length; i++) { if (this.state.board[i][position[1]] === num && position[0] !== i) { return false; } } return true; } boxIsValid(num, position) { const box_x = Math.floor(position[1] / 3); const box_y = Math.floor(position[0] / 3); for (let i = box_y * 3; i < box_y * 3 + 3; i++) { for (let j = box_x * 3; j < box_x * 3 + 3; j++) { // 修复数组比较逻辑 if (this.state.board[i][j] === num && !(i === position[0] && j === position[1])) { return false; } } } return true; }
现在你的代码应该可以正常运行,正确校验数独棋盘的合法性了。
内容的提问来源于stack exchange,提问作者andypaling1
相关产品推荐
相关产品推荐

