javascript - 为什么这个函数返回-3?
问题描述
当我尝试这个函数时,它的控制台记录为 -3,但是当我自己解决它时,它似乎会返回 12。这是为什么呢?
function func(x) {
if (x <= 0) {
return x;
}
return func(x - 5);
}
console.log(func(17));
解决方案
因为在返回时你再次调用它
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
推荐阅读
- build - 与早期 (0.8.0) 版本相比,A-Frame 的最新稳定版本 (0.9.0) 未能通过 360ImageGallery
- c# - VS17 和 TFS 17 构建要求
- git - 如何合并远程跟踪无 github 分支?
- javascript - 在 QUnit 测试中,只有在测试运行之前获得引用时才会触发 click 事件
- excel - 将字符串变量设置为单元格——应用程序定义的或对象定义的错误
- sql - 如何修复“无法删除对象 'Teams',因为它被 FOREIGN KEY 约束引用”
- graphql - 如何在一个类型中添加多个解析器(Apollo-server)
- java - Collections.sort 不改变列表
- java - MouseClicked() 方法不适用于寻路算法?
- sql - 如何避免使用 for next 方法获取行数