Javascript递归函数不返回值? [英] Javascript recursive function not returning value?

查看:81
本文介绍了Javascript递归函数不返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解决代码战问题,并且非常确定我已经解决了这个问题:

Im solving a codewars problem and im pretty sure i've got it working:

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));

基本上应该找到一个数字根":

Essentially it's supposed to find a "digital root":

数字根是数字中所有数字的递归和.给定n,取n的数字之和.如果该值有两个位数,请继续以这种方式减少,直到获得一位数生产的.这仅适用于自然数.

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 语句上(我正在监视调试器的运行并确实输入了该语句,都会说返回值是正确的值.

So im actually getting the correct answer at the end but for whatever reason on the if statement (which im watching the debugger run and it does enter that statement it will say the return value is the correct value.

但是然后它跳出了 if 语句,并尝试从主 digital_root 函数返回?

But then it jumps out of the if statement and tries to return from the main digital_root function?

这是为什么?碰到 if 语句时,它不应该突破吗?令我感到困惑的是,为什么它尝试跳出 if 语句,然后尝试从 digital_root 不返回任何内容,从而使返回值最终未定义?

Why is this? shouldn't it break out of this when it hits the if statement? Im confused why it attempt to jump out of the if statement and then try to return nothing from digital_root so the return value ends up being undefined?

推荐答案

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

You're not returning anything inside else. It should be:

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

为什么?

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

digital_root is supposed to return something. If we call it with a one digit number, then the if section is executed, and since we return from that if, everything works fine. But if we provide a number composed of more than one digit then the else section get executed. Now, in the else section we calculate the digital_root of the count but we don't use that value (the value that should be returned). The line above could be split into two lines of code that makes it easy to understand:

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递归函数不返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆