0
我想创建一个接收数字的函数,该数字将被缩减为它的数字之和(16减少到7 - >返回7),直到结果只有一位数字(326减少到11,然后减少到2 - >返回2)。JavaScript中的递归函数返回undefined
我创建一个递归函数如下,但它返回未定义的数字,其长度> 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
我已经看到了一些类似的questions,但他们只处理代码,而不是概念。我学习递归的方式是,你有一个基本的例子,你评估,如果它是真的,然后返回 - 这将是递归的结束 - 如果没有,继续并运行代码将转换数据将是再次发送进行评估。
我怎样才能避免未定义的结果,是我的递归概念准确?
'return digital_root(reducedArr)'' – Phil