JavaScript递归实现阶乘入门求助:sum未定义错误
Hey there! Let's break down why you're hitting that ReferenceError and get your factorial function working right.
The immediate issue with your code
The error ReferenceError: sum is not defined pops up because you never declared the sum variable anywhere in your function. Even if you did declare it (like let sum = 1;), using an outer-scoped or global variable for recursion is a bad practice—it would mess up results if you call the function multiple times (e.g., running nFactorial(3) then nFactorial(2) would reuse the existing sum value and give wrong outputs).
How recursive factorial is supposed to work
Recursion relies on a function calling itself with a smaller input, and using its own return values to build the final result. For factorial:
- Base case (termination rule):
0!and1!both equal 1—this stops the recursion from looping infinitely. - Recursive case:
n! = n * (n-1)!—we calculate the factorial ofn-1, multiply it byn, and return that value.
Here's the corrected recursive function
function nFactorial(n) { // Factorial isn't defined for negative numbers, handle that case if (n < 0) return null; // Base case: stop recursion when n is 0 or 1 if (n === 0 || n === 1) return 1; // Recursive case: n! = n multiplied by (n-1)! return n * nFactorial(n - 1); } // Test it out: console.log(nFactorial(3)); // Outputs 6, which is correct!
Let's walk through how this works for nFactorial(3)
n=3isn't a base case, so we return3 * nFactorial(2)n=2isn't a base case, so we return2 * nFactorial(1)n=1matches the base case, so we return1- Now we work backwards:
2 * 1 = 2, then3 * 2 = 6—that's our final result!
Alternative: Using an accumulator (if you're curious)
If you want to experiment with an accumulator variable (though the first approach is more straightforward for factorial), you can pass it as a parameter with a default value to avoid external state:
function nFactorial(n, sum = 1) { if (n < 0) return null; // Base case: when n reaches 0, return the accumulated sum if (n === 0) return sum; // Pass the updated sum to the next recursive call return nFactorial(n - 1, sum * n); }
The big takeaway here is that recursive functions should depend on their own return values and clear base cases, not external variables. This keeps them predictable and free of unexpected side effects.
内容的提问来源于stack exchange,提问作者user2785628

