简体   繁体   中英

can't understand the logic of calculation

function fac(n) {
  if (n == 0)
    return 1;
  else
    return (n - 1) * n;
};
console.log(fac(4));
// 12 

here is everything clear (4-1)*4=12

function fac(n) {
  if (n == 0)
    return 1;
  else
    return fac(n - 1) * n;
};
console.log(fac(4));
//24

here is what I get confuse is it Recursive Call? because we returning the fac function inside itself is it kind calling? I understand how to call function in general like in this example console.log(fac(4));, but I don't understand how it is calculates return fac(n - 1) * n; I f some one could explain how does the calculation going, and another thing I undarstand that code is different in this two examples one just return values but other return what? function in function .... here is where I got confused. Thank you for your time!

Yes this is a recursive call. The function continues calling itself and decrementing the argument until the value passed is 0. The function doesn't return itself, it calls itself and returns the result. This works because the function terminates and stops calling itself when it is passed 0 as an argument.

So it goes

fac(4) -> fac(3) * 4 -> fac(2) * 3 * 4 -> fac(1) * 2 * 3 * 4 -> fac(0) * 1 * 3 * 4 -> 1 * 1 * 2 * 3 * 4 -> 24

This is an example for factorial of 5, but it is the same as 4

这是我在网上找到的一个例子

try these links to learn more: http://www.c-point.com/javascript_tutorial/recursion.htm

http://www.codecademy.com/courses/javascript-lesson-205/0/1

Yes it is called recursion.

The value gets calulated for fac(4) are as follows:

fac(4) = fac(3) * 4
fac(3) = fac(2) * 3
fac(2) = fac(1) * 2
fac(1) = fac(0) * 1
fac(0) = 1

So eventually it will be like

 fac(4) = 1 * 1 * 2 * 3 * 4

This is how it gets evaluated and thus you get your factorial value.

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