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

JS递归函数尝试返回值时得到undefined,如何获取正确的factor结果

问题原因

递归返回undefined的核心问题是递归调用分支没有添加返回语句:当进入else分支执行findFactor(nextFactor, width)时,你只是触发了递归调用,但没有将这个调用的返回值向上层传递,上层的函数调用无法拿到底层递归返回的nextFactor,最终就会返回默认的undefined。

修复方案

只需要在else分支的递归调用前加上return关键字即可,修改后的代码如下:

function findFactor(factor, width) {
  let nextFactor = factor - 0.05;
  let value = width * nextFactor;

  console.log(nextFactor);

  if (value < 900) {
    return nextFactor;
  } else {
    // 新增return关键字,将递归结果向上传递
    return findFactor(nextFactor, width);
  }
}

console.log(findFactor(1, 2400));

运行上述代码会得到输出结果0.3700000000000001,如果对浮点数精度有要求,可以自行添加toFixed等精度处理逻辑。

内容的提问来源于stack exchange,提问作者s.khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 09:36:04