[英]Why code still run to the end of recursive function?
我认为以下代码永远不会到达console.log
行,因为next()
函数之前已经运行到达console.log
行,而if else
条件带有return
也会阻止它,但事实并非如此。 为什么?
var arr = ['a', 'b', 'c'];
var i = 0;
function next() {
if (i < arr.length) {
next(i++);
console.log('why go here 1:' + i); // 3,3,3
} else {
return;
}
console.log('why go here 2:' + i); // 3,3,3
}
next();
一旦满足边缘条件,这些对next()
调用将返回(在这种情况下,一旦i
大于arr.length
)。 这是递归的一部分,通常称为“展开” - 每个递归调用都返回为它调用的调用返回。 所以一旦next()
函数返回,它继续到console.log()
您可以调整代码,使其在函数启动时记录,并返回计数以显示递归:
var arr = ['a', 'b', 'c']; let i = 0; let space = 1 function next() { let s = space++ console.log(" ".repeat(s) + `next ${s} called`) if (i < arr.length) { next(i++); } else { console.log("edge condition -- finally start unwinding") console.log(" ".repeat(s) + `next ${s} retured from edge condition`) return; } console.log(" ".repeat(s) + `next ${s} retured`) } next();
在这里你可以看到调用的四个next()
函数没有返回,但是一旦你达到边缘条件,它们就会以相反的顺序展开并返回。
您需要使用调试器或笔/纸来逐步完成它以完全理解流程。
当next(i++)
返回时,就像在任何函数调用之后一样,它将转到下一行。 如果您希望代码停止,则必须在调用next(i++)
后return
。 例如: return next(i++);
或者next(i++); return;
next(i++); return;
if
语句/函数将运行范围内的所有内容,除非有诸如break
之类的东西来终止当前循环,开关或标签语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.