二维数组正负梯度搜索问题:scanForPositiveGradientCombinations函数报错排查
问题分析与修复
错误原因
你遇到的TypeError确实是rowIndex递减导致数组越界引发的:
- 正梯度搜索函数中,
rowIndex不断递减,当它变为负数时,rowCellValues[rowIndex]会返回undefined - 此时继续访问
rowCellValues[rowIndex][columnIndex]或者判断columnIndex < rowCellValues[rowIndex].length,都会因为undefined没有对应属性/下标而触发TypeError - 原while循环只判断了
rowIndex < rowCellValues.length(防止行下标过大),但完全没限制rowIndex不能小于0
修复后的正梯度搜索函数
修改scanForPositiveGradientCombinations的循环条件,加上rowIndex >= 0的判断,确保每一步的行、列下标都在有效范围内:
const scanForPositiveGradientCombinations= (columnIndex, rowIndex, rowCellValues, playerSymbol, winCountCondition) => { let counter = 0; // 新增rowIndex >= 0的判断,避免行下标越界 while(rowIndex >= 0 && rowIndex < rowCellValues.length && columnIndex < rowCellValues[rowIndex].length){ if(rowCellValues[rowIndex][columnIndex] === playerSymbol){ counter++; } if(counter >= winCountCondition){ return true; } rowIndex--; columnIndex++; } return false; }
额外优化建议
如果你的二维数组存在行长度不一致的情况,可以进一步优化循环逻辑,提前判断当前行是否有效:
const scanForPositiveGradientCombinations= (columnIndex, rowIndex, rowCellValues, playerSymbol, winCountCondition) => { let counter = 0; while(rowIndex >= 0 && rowIndex < rowCellValues.length){ const currentRow = rowCellValues[rowIndex]; // 提前判断当前行是否存在、列下标是否超出当前行长度 if(!currentRow || columnIndex >= currentRow.length){ break; } if(currentRow[columnIndex] === playerSymbol){ counter++; } if(counter >= winCountCondition){ return true; } rowIndex--; columnIndex++; } return false; }
内容的提问来源于stack exchange,提问作者Mikeyjpk
相关产品推荐
相关产品推荐

