JS 递归函数中断

JS Recursive Function Breaking

我使用递归函数已经有一段时间了,我对当前的问题感到非常困惑。这是我的代码:

var setbackArray = new Array();
setbackArray = [5, 15, 20];
var positionArray = new Array();
positionArray = ["28.0", "28.0", "24.4", "24.4", "24.4", "28.0", "28.0", "28.0", "28.0", "28.0", "24.4", "28.0", "28.0", "28.0", "24.4", "24.4", "24.4", "24.4", "24.4", "24.4", "24.4", "24.4", "24.4", "24.4", "18.5", "18.5", "18.5", "18.5", "22.1", "22.1", "22.1", "22.1", "28.0", "28.0", "28.0", "28.0", "38.6", "38.6", "32.7", "32.7", "38.6", "32.7", "38.6", "32.7", "32.7", "38.6", "38.6", "38.6", "32.7", "32.7", "32.7", "38.6", "32.7", "38.6", "32.7", "38.6", "43.2", "43.2", "43.2", "43.2", "43.2", "43.2", "43.2", "43.2", "43.2", "43.2", "43.2", "43.2", "43.2", "43.2", "43.2", "43.2", "43.2", "43.2", "43.2", "43.2", "22.1", "22.1", "22.1", "22.1", "22.1", "22.1", "22.1", "22.1", "22.1", "22.1", "32.7", "32.7", "32.7", "32.7", "38.6", "38.6", "38.6", "38.6"]
var recursive = function (i, length) {
    console.log('i: ' + i + ', length: ' + length);
    if (i < length) {
        var seatposition = Number(positionArray[i]).toFixed(1);
        console.log(seatposition);
        if (seatposition < setbackArray[setbackArray.length - 1] + 20 && seatposition > setbackArray[0] - 20) {
            console.log('Doing Some Math.....');
        } else {
            console.log('Not Usable');
            recursive(++i, length);
        }
        console.log('Doing More Math.......');
        console.log('Doing Even More Math.......');
        console.log('Doing Last Bit Of Math.......');
        console.log('Display Stuff On Screen');
        recursive(++i, length);
    } else {
        console.log('done checking');
    }
}
recursive(0, positionArray.length);

在实际代码中,两个数组都是动态创建的,我只是在这里编写代码,以便您有一个真实的示例。基本上,我要遍历 positionArray 中的所有数字,看看该数字是否小于 setbackArray 中的最高数字加上 20,并且大于 setbackArray 中的最小数字减去 20。如果是,我用它做一些数学计算稍后使用。如果不是,我希望它移动到 positionArray 中的下一个数字。

我 运行 遇到的问题是一旦 i < length 不再为真,它显示 "done checking" 然后将 i 重置为以前的值并继续 运行 .它无休止地这样做并使整个页面崩溃。

我知道问题出在这里:

} else {
      console.log('Not Usable');
      recursive(++i, length);
}

如果我删除递归标注,它 运行 正常但会执行我不想对该数字执行的额外数学运算。

有什么想法吗?

工作样本here

看来您在有问题的 else 块中的意图实际上是:

    } else {
        console.log('Not Usable');
        return recursive(++i, length);
    }

这将使函数的其余部分短路以获得 "not usable" 值。

就像现在一样,您在该场景中递归调用您的函数两次,随着递归沿着多条路径继续进行,导致分叉的控制流。

重构和修复该部分的另一种方法是:

    var seatposition = Number(positionArray[i]).toFixed(1);
    console.log(seatposition);
    if (seatposition < setbackArray[setbackArray.length - 1] + 20 && seatposition > setbackArray[0] - 20) {
        console.log('Doing Some Math.....');
        console.log('Doing More Math.......');
        console.log('Doing Even More Math.......');
        console.log('Doing Last Bit Of Math.......');
        console.log('Display Stuff On Screen');
    } else {
        console.log('Not Usable');
    }
    recursive(++i, length);