阶乘代码有效,但是为什么 [英] Factorial Code works but why

查看:47
本文介绍了阶乘代码有效,但是为什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解决一个阶乘问题,该函数需要一个数字并返回该数字的阶乘.

I'm solving a factorial problem where the function takes a number and returns the factorial of that number.

我遇到的问题是代码可以工作,但我不知道为什么.执行代码后没有循环可以调用它,我什至不确定当前值的存储位置.如果我是对的,我认为函数每次在返回时都会重新运行,并且以n-1的值运行,因此比上一次运行的数字少一个数字,但是,我仍然看不到该值如何被当前值存储到多个数字中.即使我在每次运行后记录n的当前值,我得到的数字都是10到1.我认为当前值将变为乘数.

The problem I'm running into is that the code works but I don't know why. There are no loops to call it back after the code is executed and I'm not even sure where the current value is being stored.If I am correct the I assume the function is re-running every time it hit the return and it is running with a value of n-1 so one number less than the previous time it ran, however, I still do not see how the value is getting stored to multiple each number by the current value. Even if I log the current value of n after every run all I get is the numbers 10 down to one. I would think the current value would change to the multiplied value.

同样,此代码可以完美运行,我只需要了解原因.

Again this code works perfectly I just need to understand why.

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

factorial(10);

推荐答案

您在这里拥有的是递归函数-一个可以自我调用的函数.您还需要牢记函数中变量的作用域".

What you have here is a recursive function - a function which calls itself. You also need to keep in mind the "scope" of the variables in the function.

参数"n"的范围是该函数的局部范围.每次调用该函数时,都会创建新变量.每个变量的范围是函数执行.

The scope of the parameter "n" is local to the function. Every time the function is called, the new variable is created. The scope of each variable is the function execution.

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

示例:

Parameter Value = 0
Hence, n = 0
Execute factorial(0)
1. line 1: variable n = 0
2. line 2: check if n = 0
3. line 3: return 1

示例:

Parameter Value = 2
Hence, n = 2
Execute factorial(2)
1. line 1: variable n = 2 (scope = execution #A)
2. line 5: console log n = 2
3. line 6: return 2 * factorial(2-1) // Function calls itself
    4. line 1: variable n = 1 (scope = execution #B)
    5. line 5: console log n = 1
    6. line 6: return 1 * factorial(1-1) // Function calls itself
        7. line 1: variable n = 0 (scope = execution #C)
        8. line 3: return 1 // #C returns 1
    9. return 1 * 1 // #B returns 1 * 1 (from #C)
10. return 2 * 1 // #A returns 2 * 1 (from #B)

这篇关于阶乘代码有效,但是为什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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