JS递归函数分解

时间:2015-01-27 20:47:00

标签: javascript recursion

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

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中的下一个数字。

我遇到的问题是,一旦我&lt;长度不再是真的,它显示&#34;完成检查&#34;然后将i重置为之前的值并继续运行。它没有结束并且崩溃了整个页面。

我知道问题就在这里:

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

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

有什么想法吗?

工作样本here

1 个答案:

答案 0 :(得分:2)

您在确定的问题else块中的意图实际上是:

    } else {
        console.log('Not Usable');
        return recursive(++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.....');
        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);