简体   繁体   English

为什么阶乘 function 返回的不是 1?

[英]Why factorial function return not 1?

I can't understand why the function returned a result and not a unit, how does it work?我不明白为什么 function 返回结果而不是单位,它是如何工作的?

function factorial(n) {
  return (n != 1) ? n * factorial(n - 1) : 1;
}

console.log(factorial(5)); // result is 120 why not 1 ?

This is a recursive function. You start by passing in 5 .这是一个递归的 function。您首先传入5 It then calls itself with 4 , and so on.然后它用4调用自己,依此类推。 The math for each call looks like this:每个调用的数学运算如下所示:

factorial(5): 5 * factorial(4)
factorial(4): 4 * factorial(3)
factorial(3): 3 * factorial(2)
factorial(2): 2 * factorial(1)
factorial(1): 1

Once you get to the "base case", 1, execution goes back up the stack in reverse order and uses the result of each previous step:一旦到达“基本情况”1,执行将以相反的顺序返回堆栈并使用每个先前步骤的结果:

factorial(1): 1
factorial(2): 2 * 1 = 2
factorial(3): 3 * 2 = 6
factorial(4): 4 * 6 = 24
factorial(5): 5 * 24 = 120

And so factorial(5) returns 120.所以 factorial(5) 返回 120。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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