JavaScript递归调用结果存储位置及反转函数异常问题咨询
Great question! Let's unpack this clearly, using your examples to illustrate exactly what's happening.
核心答案:递归结果存在**调用栈(Call Stack)**的执行上下文中
Every time you call a function—recursive or not—JavaScript creates an Execution Context: a small container that holds the function's parameters, local variables, and the value it will eventually return. All these contexts are stacked up in the Call Stack.
For recursive functions, each nested call adds a new context to the top of the stack. When a call hits the base case (like str.length == 1 in your example), it returns a value, which gets passed back down to the context that called it. That context uses that value to compute its own return value, and so on until the original call at the bottom of the stack finishes.
Let's break down your broken example first
function reverse(str){ if (str.length == 1){ return str; } rev = reverse(str.substr(1)) + str.charAt(0); } reverse("String"); console.log(rev); // ----> "undefinedS"
Here's why this fails:
- You're missing a
returnfor the recursive case! The function only returns something whenstr.length == 1— all other calls don't explicitly return anything, so they implicitly returnundefined. - The variable
revis global (you didn't declare it withlet,const, orvar), so it only holds the value from the last time that line ran. That last run is the original call toreverse("String"), wherereverse(str.substr(1))returnsundefined(since that recursive call had no return), then you addstr.charAt(0)("S") — henceundefinedS.
The fixed example works because of that critical return
function reverse(str){ if (str.length == 1){ return str } return reverse(str.substr(1)) + str.charAt(0); } reverse("String") // ----> "gnirtS"
Now, every recursive call returns its computed value to the caller. Let's walk through the stack step by step:
reverse("String")callsreverse("tring")reverse("tring")callsreverse("ring")- ... this continues until
reverse("g")hits the base case and returns"g" reverse("ng")takes"g"+"n"and returns"gn"reverse("ing")takes"gn"+"i"and returns"gni"- This keeps going up the stack until
reverse("String")takes"gnirt"+"S"and returns"gnirtS"
Each step's result is stored in its own execution context in the call stack, and passed back up to the parent call via the return statement.
内容的提问来源于stack exchange,提问作者coool

