条件语句中的空返回语句如何起作用?

从 MDN Docs 学习 JS 遇到了“函数部分”中的代码。无法理解return;以下代码完成了什么


function foo(i) {

  if (i < 0)

    return; // what does this do? 

  console.log('begin: ' + i);

  foo(i - 1);

  console.log('end: ' + i);

}

foo(3);


Output


'begin: 3'

'begin: 2'

'begin: 1'

'begin: 0'

'end: 0'

'end: 1' // why are these printing

'end: 2' // this one

'end: 3' // this one

我理解了前 5 行输出,但无法理解为什么end: 0,1,2,3会出现?


请帮忙 !


慕妹3146593
浏览 161回答 3
3回答

天涯尽头无女友

return终止当前函数,并将控制流返回给调用者。当foo(3);被调用时,函数用i参数 3初始化。它使if语句失败,打印begin: 3,然后调用foo(3 - 1);。此时,当前函数(i参数为 3的函数)将暂停,直到foo(3 - 1);调用完成。foo(2);打印begin: 2,然后在调用时暂停foo(1)。foo(1)打印begin: 1,然后在调用时暂停foo(0)。foo(0)打印begin: 0,并返回:它终止,并将控制流返回给它的调用者,即 的函数调用foo(1)。foo(1)恢复,并继续执行,打印end: 1。这是函数块的结尾,因此foo(1)函数调用结束,将控制流返回到foo(2)函数调用。foo(2)恢复,打印end: 2,然后终止,产生控制流回到foo(3)。然后foo(3)打印end: 3,并终止。return仅终止当前功能。终止所有调用函数(直到catch遇到 a)的唯一方法是抛出错误:function foo(i) {&nbsp; if (i < 0)&nbsp; &nbsp; throw new Error();&nbsp; console.log('begin: ' + i);&nbsp; foo(i - 1);&nbsp; console.log('end: ' + i);}foo(3);

MMTTMM

这应该可以帮助您跟踪代码:foo(3)|-- "begin 3"|-- foo(2)|&nbsp; &nbsp;|-- "begin 2"|&nbsp; &nbsp;|-- foo(1)|&nbsp; &nbsp;|&nbsp; &nbsp;|-- "begin 1"|&nbsp; &nbsp;|&nbsp; &nbsp;|-- foo(0)|&nbsp; &nbsp;|&nbsp; &nbsp;|&nbsp; &nbsp;|-- "begin 0"|&nbsp; &nbsp;|&nbsp; &nbsp;|&nbsp; &nbsp;|-- foo(-1) // returns nothing|&nbsp; &nbsp;|&nbsp; &nbsp;|&nbsp; &nbsp;|-- "end 0"|&nbsp; &nbsp;|&nbsp; &nbsp;|-- "end 1"|&nbsp; &nbsp;|-- "end 2"|-- "end 3"

三国纷争

这是一个递归函数。当基本条件填充时,它执行其他语句。在你的情况下它是 console.log('end: ' + i);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript