我想创建一个接收数字的函数,该数字将减少为其数字的总和(16减少为7->返回7),直到结果只有一位数字长(326减少为11,然后减少到2->返回2)。
我正在创建如下的递归函数,但是对于长度大于1的数字,它返回undefined。
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
我已经看到了一些类似的问题,但是它们仅解决代码问题,而不涉及概念。我学习递归的方式是,您有一个评估的基本案例,如果为真,则返回-这将是递归的结尾-如果不是,请继续运行将转换数据的代码。再次发送以进行评估。
如何避免未定义的结果,并且我的递归概念是否正确?
return digital_root(reducedArr);
您return
在else
分支中缺少。function
不执行的Areturn
将产生undefined
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句