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

JavaScript中返回数字时Number转为undefined的问题排查

问题解决:递归链表取值函数返回undefined的原因

你的nth函数问题出在递归调用时没有返回结果!

先看你的原代码:

function nth (list, number) {
  if (number !== 0) {
    nth(list.rest, number - 1) // 这里缺少return!
  } else {
    console.log(typeof list.value)
    return list.value
  }
}

当number不等于0时,你确实发起了递归调用去遍历下一个链表节点,但没有把递归调用的结果返回给上层调用栈。这就导致除了number=0的情况(此时直接return了list.value),其他所有递归分支执行完后,当前函数没有返回值,JavaScript会默认返回undefined。

修正后的代码

只需要在递归调用前加上return即可:

function nth (list, number) {
  if (number !== 0) {
    // 把递归调用的结果返回给上层
    return nth(list.rest, number - 1)
  } else {
    console.log(typeof list.value)
    return list.value
  }
}

额外的健壮性优化

如果传入的number超过了链表的长度,遍历到最后list会变成null,此时访问list.value会报错。可以加个边界判断:

function nth (list, number) {
  // 链表已遍历完,直接返回undefined避免报错
  if (!list) return undefined;
  if (number !== 0) {
    return nth(list.rest, number - 1)
  } else {
    console.log(typeof list.value)
    return list.value
  }
}

这样不管number是否超出链表长度,函数都能安全执行啦~

内容的提问来源于stack exchange,提问作者Mathemagician

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:46:14