要防止JavaScript遞歸函數(shù)的無(wú)限循環(huán),您可以采取以下措施:
function factorial(n) {
if (n === 0 || n === 1) {
return 1;
}
return n * factorial(n - 1);
}
function recursiveFunction(depth, maxDepth) {
if (depth > maxDepth) {
console.error("Reached maximum recursion depth");
return;
}
// Your recursive logic here
recursiveFunction(depth + 1, maxDepth);
}
for
循環(huán)或while
循環(huán)),并利用數(shù)據(jù)結(jié)構(gòu)(如棧)來(lái)存儲(chǔ)待處理的任務(wù)。這有助于避免無(wú)限遞歸的風(fēng)險(xiǎn)。function iterativeFunction(data) {
const stack = [...data];
while (stack.length > 0) {
const currentItem = stack.pop();
// Process the current item
}
}
總之,要防止JavaScript遞歸函數(shù)的無(wú)限循環(huán),請(qǐng)確保您的函數(shù)具有明確的終止條件,限制遞歸深度,并在適當(dāng)?shù)那闆r下使用迭代方法。