为什么来自Eloquent JavaScript的这个函数示例返回值24? [英] Why does this function example from Eloquent JavaScript return the value 24?

查看:89
本文介绍了为什么来自Eloquent JavaScript的这个函数示例返回值24?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JavaScript新手,想要从书中理解一个例子。当我通过这个例子时,我预计fac(4)的值是12.这将是(4 - 1)* 4的结果。然而,

然而, ,当我在 http://eloquentjavascript.net/00_intro上运行在线书籍(页面底部附近)的代码时。 html ,我得到的值是24.我在这里错过了什么?

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

我试图通过Twitter和在线调查找到答案,但都不成功。我知道我忽略了一些东西,但似乎无法看到它。 解决方案

因为它是递归的。

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

所以让我们来追踪它
$ b $ pre > fac(3)* 4;
fac(2)* 3 * 4;
fac(1)* 2 * 3 * 4;
fac(0)* 1 * 2 * 3 * 4;
1 * 1 * 2 * 3 * 4;

当然,这是24。


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.

解决方案

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.

这篇关于为什么来自Eloquent JavaScript的这个函数示例返回值24?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆