首页 > 解决方案 > 为什么这个函数返回-3?

问题描述

当我尝试这个函数时,它的控制台记录为 -3,但是当我自己解决它时,它似乎会返回 12。这是为什么呢?

function func(x) {
  if (x <= 0) { 
    return x; 
  }
  return func(x - 5);
}
console.log(func(17));

标签: javascriptfunction

解决方案


因为在返回时你再次调用它

function func(x) { <-- x=17

if (x <= 0) { 
return x; 
}
 return func(x - 5); <---x=12 so now you call the func with 12
}
console.log(func(17));

第2步

function func(x) { <-- x=12

if (x <= 0) { 
return x; 
}
 return func(x - 5); <---x=7 you call with 7 
}
console.log(func(17));

第 3 步

function func(x) { <-- x=7

if (x <= 0) { 
return x; 
}
 return func(x - 5); <---x=2 you call with 2
}
console.log(func(17));

第4步

function func(x) { <-- x=2

if (x <= 0) { 
return x; 
}
 return func(x - 5); <---x=-3 you call with -3
}
console.log(func(17));

最后一步

function func(x) { <-- x=-3

if (x <= 0) { 
return x; <--- now you print the result
}
 return func(x - 5); 
}
console.log(func(17));

编辑:

递归函数是在中断条件为真之前调用自己的函数,在您的示例中,中断条件是 x 等于 (=) 或小于 (<) 小于 0,然后打印结果。

使用 17 你得到的第一个数字是 5 返回 true 的 con break 条件是 -3


推荐阅读