简体   繁体   English

Javascript中的递归函数返回未定义

[英]Recursion function in Javascript return undefined

function right(a,b){ 
if( a > b) { 
  console.log(b+1);
  return b +1 ; } 
else 
{ 
  right(a +=1,b);
  console.log(a); } 

}

When I call this function it returns undefined. 当我调用此函数时,它返回未定义。 right(5,10) // undefined. right(5,10)//未定义。 Can anyone one help me why when the variable b is declared and has the value. 谁能帮我解释为什么变量b被声明并具有值。

Basically you need to return on the else part something as well. 基本上,您还需要返回其他部分。

function right(a,b){ 
    if( a > b) { 
        console.log(b + 1); 
        return b + 1;
    } else {
       console.log(a + 1);
       return right(a + 1, b);
       // ^^^
    } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM