简体   繁体   中英

Recursive function in Javascript returns undefined

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM