You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 return for the recursive case! The function only returns something when str.length == 1 — all other calls don't explicitly return anything, so they implicitly return undefined.
  • The variable rev is global (you didn't declare it with let, const, or var), so it only holds the value from the last time that line ran. That last run is the original call to reverse("String"), where reverse(str.substr(1)) returns undefined (since that recursive call had no return), then you add str.charAt(0) ("S") — hence undefinedS.

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:

  1. reverse("String") calls reverse("tring")
  2. reverse("tring") calls reverse("ring")
  3. ... this continues until reverse("g") hits the base case and returns "g"
  4. reverse("ng") takes "g" + "n" and returns "gn"
  5. reverse("ing") takes "gn" + "i" and returns "gni"
  6. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:33:43