You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

二维数组正负梯度搜索问题: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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 09:31:01