JavaScript报错isPalindrome is not a function问题排查
报错根源
你遇到的TypeError: isPalindrome is not a function错误,本质是isNotPalindrome运行时,内部名为isPalindrome的形参接收到的值不是函数类型,常见触发场景有两种:
- 调用
isNotPalindrome时漏传参数,或者传入的是字符串、数字、布尔值等非函数类型的值 - 传参时错误地给
isPalindrome加了括号,比如写成isNotPalindrome(isPalindrome("abc")),这时候传入的是isPalindrome("abc")的执行结果(布尔值),不是函数本身
除此之外你的代码还有两个逻辑问题:
- 你定义的
isPalindrome本身需要接收text作为入参才能运行,但你在isNotPalindrome内部调用它时没有传任何参数 - 你在
isNotPalindrome内部只对判断结果做了取反操作,没有把最终结果返回,外部调用这个函数永远只能得到undefined
修正后的可运行代码
const isPalindrome = (text) => { let text1 = text.toLowerCase(); let text2 = text1.split('').reverse().join(''); return text1 === text2; } // 高阶函数写法:第一个参数接收判断函数,第二个参数接收待校验的文本 const isNotPalindrome = (checkFn, text) => { // 传入待校验文本执行判断,取反后返回结果 return !checkFn(text); }; // 调用示例 console.log(isNotPalindrome(isPalindrome, "Level")); // 输出 false,Level是回文 console.log(isNotPalindrome(isPalindrome, "hello")); // 输出 true,hello不是回文
补充说明
如果你的需求只是做回文的反向判断,不需要做通用的高阶函数(即不需要接收任意判断函数做反向逻辑),可以直接简化写法,不用传函数入参:
const isNotPalindrome = (text) => { const normalizedText = text.toLowerCase(); const reversedText = normalizedText.split('').reverse().join(''); return normalizedText !== reversedText; };
内容的提问来源于stack exchange,提问作者Anna Andreevna
相关产品推荐
相关产品推荐

