Javascript 中的递归函数返回未定义 [英] Recursive function in Javascript returns undefined

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

问题描述

我想创建一个函数,接收一个数字,这个数字会减少到它的数字之和(16减少到7->返回7)直到结果只有一位长(326减少到11)然后减少到 2 -> 返回 2).

I want to create a function that receives a number, the number will be reduced to the sum of its digits (16 is reduced to 7 -> return 7) until the result is just one digit long (326 is reduced to 11 and then reduced to 2 -> return 2).

我正在创建一个递归函数,如下所示,但对于长度大于 1 的数字,它返回 undefined.

I am creating a recursive function as follows, but it returns undefined for digits whose length is > 1.

function digital_root(n) {
   var numStr = (typeof n == "string") ? n : n.toString(); // ensure we will use a string
   //console.log("evaluating " + numStr + "its length is " + numStr.length);
   //now evaluate my base case
   if (numStr.length <= 1){
     console.log("i will return" + numStr)//should return my 1 digit number
     return n; //it doesn't
   }
   else{
     var arr = numStr.split(""); //convert the string into an array
     var reducedArr = arr.reduce(function(a,b){
       return parseInt(a) + parseInt(b);//sum the elements of the array
     });
     digital_root(reducedArr);//send the reduced value back for evaluation
  }
}
digital_root(16)//returns undefined

我见过一些类似的问题,但它们只解决了代码和不是概念.我学习递归的方式是,您有一个基本情况可以评估,如果为真,则返回 - 这将是递归的结束 - 如果不是,请继续运行将转换数据的代码再次发送评估.

I've seen a few similar questions but they address only the code and not the concept. the way i've learned recursion is that you have a base case that you evaluate, if it's true then return -this will be end of the recursion-, if not, go ahead and run the code that will transform the data that will be sent again for evaluation.

如何避免未定义的结果,我的递归概念是否准确?

how can I avoid the undefined result and is my conception of recursion accurate?

推荐答案

return digital_root(reducedArr);

您在 else 分支中缺少 return.不执行 returnfunction 将产生 undefined.

You are missing a return in the else branch. A function that does not execute return will yield undefined.

这篇关于Javascript 中的递归函数返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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