【发布时间】:2019-07-16 04:59:06
【问题描述】:
我创建了这个递归函数来计算一个数字的阶乘。第一个参数 n 是您要为其计算阶乘的数字,第二个参数 result 用于在调用自身时将阶乘计算的状态传递给函数。我遇到的问题是该函数将在函数结束时控制台记录正确的阶乘结果,但不会返回它。它只会返回小于 2 的数字的阶乘,所有其他返回未定义。我有一个带有“n > = 2”的条件,所以这让我认为这与此有关,但是我找不到这与问题之间的任何关系。为什么这个函数没有返回正确的阶乘?
function factorial(n, result){
//checks if result is undefined if so uses n calculate value of result
//if result isnt undefined it changes its value using "n * ( n - 1)"
result = result * (n - 1) || n * (n - 1);
//decreases n, n gets gradually smaller
n-=1;
//if n is more the 2 run function again
//I'm fairly certain this conditional is the root of the issue but personally cant find the relation
if(n >= 2){
//passes current state of n and result
factorial(n,result);
}
else {
//result has the correct value as its printing to the console
//correctly, e.g !4 = 4*3*2*1, which equals 24, this prints 24 if you
//pass 4 to n.
console.log(result);
//if n is smaller then 2 return factorial
//but it wont return result
return result;
};
}
【问题讨论】:
-
您的
if分支中没有return语句,因此它返回undefined。 -
改变阶乘(n,result);到“返回阶乘(n,结果);”阶乘函数只会在 n2 时它只调用函数并且不返回任何内容
-
好的,谢谢 melpomene 和 yash Thakor
标签: javascript recursion