gpt4 book ai didi

Javascript 递归函数不返回值?

转载 作者:行者123 更新时间:2023-11-30 07:33:13 25 4
gpt4 key购买 nike

我正在解决一个 codewars 问题,我很确定我已经成功了:

function digital_root(n) {
// ...
n = n.toString();
if (n.length === 1) {
return parseInt(n);
} else {
let count = 0;
for (let i = 0; i < n.length; i++) {
//console.log(parseInt(n[i]))
count += parseInt(n[i]);
}
//console.log(count);
digital_root(count);
}
}

console.log(digital_root(942));

本质上它应该找到一个“数字根”:

A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has two digits, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers.

所以我实际上在最后得到了正确的答案,但是由于 if 语句的任何原因(我正在观察调试器运行并且它确实输入了该语句它会说返回值是正确的值(value)。

但是它会跳出 if 语句并尝试从主 digital_root 函数返回?

这是为什么?当它遇到 if 语句时,它不应该突破这个吗?我很困惑为什么它会尝试跳出 if 语句,然后尝试从 digital_root 返回任何内容,所以返回值最终是未定义的?

最佳答案

您不会在 else 中返回任何内容。应该是:

return digital_root(count);
^^^^^^^

为什么?

digital_root 应该返回一些东西。如果我们用一位数字调用它,则执行 if 部分,并且由于我们从 if 返回,所以一切正常。但是,如果我们提供一个由多于一位数字组成的数字,那么将执行 else 部分。现在,在 else 部分,我们计算 countdigital_root 但我们不使用该值(应返回的值) .上面这行可以分成两行代码,这样更容易理解:

var result = digital_root(count); // get the digital root of count (may or may not call digital_root while calculating it, it's not owr concern)
return result; // return the result of that so it can be used from the caller of digital_root

关于Javascript 递归函数不返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43648136/

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