我已经使用递归函数有一段时间了,我对当前的问题完全感到困惑。这是我的代码:
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 不再为真,它会显示“完成检查”,然后将 i 重置为以前的值并继续运行。它会无休止地执行此操作并使整个页面崩溃。
我知道问题就在这里:
} else {
console.log('Not Usable');
recursive(++i, length);
}
如果我删除递归标注,它会正常运行,但会执行我不想对该数字执行的额外数学运算。
有什么想法吗?
工作示例 here
最佳答案
看来您在您确定的有问题的 else
block 中的意图实际上是:
} else {
console.log('Not Usable');
return recursive(++i, length);
}
这会将函数的其余部分短路为“不可用”值。
就像现在一样,在这种情况下,您会递归调用函数两次,当递归沿着多个路径继续进行时,会导致控制流 fork 。
重构和修复该部分的另一种方法是:
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);
关于javascript - JS 递归函数破解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28179694/