gpt4 book ai didi

javascript - 为什么这个函数返回-3?

转载 作者:行者123 更新时间:2023-11-28 11:44:39 25 4
gpt4 key购买 nike

当我尝试这个函数时,它的控制台记录为-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 中断条件是 -3

关于javascript - 为什么这个函数返回-3?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54672035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com