Why does this function example from Eloquent JavaScript return the value 24?

最后都变了- 提交于 2020-01-05 08:35:22

问题


I am new to JavaScript and am trying to understand an example from the book. When I step through this example, I expect the value of fac(4) to be 12. That would be the result of (4 - 1) * 4.

However, when I run the code from the online book (near bottom of page) at http://eloquentjavascript.net/00_intro.html, I get the value 24. What am I missing here?

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

I have tried to find an answer through Twitter and through online research but have been unsuccessful. I know I am overlooking something, but can't seem to see it.


回答1:


Because it is recursive.

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

So let's trace it

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

And of course, that is 24.




回答2:


If you notice your code, at line 5 this function is calling itself, this is called recursion, read more about it on wikipedia

Lets comeback to your code and dry run it to see how it works. lets give each line a number so we can refer it

1.function fac(n) {
2.  if (n == 0)
3.    return 1;
4.  else
5.    return fac(n - 1) * n;
6.}
7.console.log(fac(4));

your input value is 4 for first call lets call it call A.

for value 4 if condition at line 1 will return false so it would go to line 5 which again calls

fac(3) * 4;

now your function call A is paused here and makes a call B with value 3. Result of call A is yet to be evaluated.

Now with value 3 this if condition at line 2 will return false again and code at line 5 will execute like above; i.e.

fac(2) * 3;

call B paused here and there will be call C with input 2 of the same function.

on call C you code will return false against if condition at line 2 so it will make call D with input 1. i.e.

fac(1) * 2

For call D if condition at line 2 will return true and your function will return 1 so the call D gets evaluated at with value 1. now replace each fac(n) from bottom to top and keep on evaluating each call.

result of call D => 1  
result of call C => fac(1) * 2 => 1 * 2 => 2  
result of call B => fac(2) * 3 => 2 * 3 => 6  
result of call A => fac(3) * 4 => 6 * 4 => 24

I hope you will be able to understand how it really works, important point in recursion is the stop condition which you code has it at line 2.

Above result can also be produced by using loops but using recursion is more fun.

Happy Coding :)



来源:https://stackoverflow.com/questions/27595015/why-does-this-function-example-from-eloquent-javascript-return-the-value-24

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!