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
相关产品推荐
相关产品推荐

