JavaScript中函数console.log正常打印但return返回undefined如何解决?
问题根因
- 递归分支缺少显式
return语句:你在else逻辑块中调用了isPalindrome(s),但没有将递归调用的结果返回,当函数执行到该分支时,没有对应return值的情况下,JavaScript会默认返回undefined。哪怕内层递归已经正确返回了true/false,外层函数也接收不到这个结果,最终输出就是undefined。 - 递归分支未写return是绝大多数递归函数返回非预期undefined的核心诱因
修复方案
仅需要在else分支的递归调用前添加return关键字即可,修复后的代码如下:
var isPalindrome = function(s) { s = s.replace(/[^A-Z]+/ig, "").toLowerCase(); if(s[0] !== s[s.length-1]) { console.log("entered false"); return false; } else if (s.length < 2 ){ console.log("entered true"); return true; } else { s = s.substring(1,s.length-1) return isPalindrome(s) // 新增return语句,返回递归调用结果 } };
- 修复后调用该函数可以正常返回布尔值,例如输入
isPalindrome("race a car")会返回false,输入isPalindrome("A man, a plan, a canal: Panama")会返回true
内容的提问来源于stack exchange,提问作者Frankycha
相关产品推荐
相关产品推荐

