freeCodeCamp回文检测项目迁移为独立HTML项目后运行异常求助
回文检测项目问题修复方案
存在的问题
- 特殊字符处理逻辑错误:代码中
replaceAll("(", ")")的写法会把所有左括号替换为右括号,直接破坏原字符串的对称结构,例如输入(121)会被处理为)121),直接导致校验失败。你在freeCodeCamp编辑器能正常运行,是因为官方测试用例没有覆盖带左括号的输入场景,没触发这个BUG。 - 结果判断逻辑错误:两个
if判断相互独立,只要存在一对不相等的字符就会先弹出「不是回文」,但只要存在任意一对相等的字符又会弹出「是回文」,会同时弹出两个错误提示,逻辑完全混乱。 - 特殊字符替换规则不完善:逐个枚举要替换的符号容易遗漏,
\、*、#等符号都未覆盖,会影响校验结果。 - HTML语法错误:表单标签误写为
<forms>,正确语法为<form>。
修正后的代码
JS代码(palindrome.js)
function palindrome() { const str = document.getElementById("palind").value.trim(); // 先判空处理 if (!str) { alert("无效输入"); return; } // 用正则直接过滤所有非字母数字的字符,无需逐个替换 const cleanStr = str.toLowerCase().replace(/[^a-z0-9]/g, ''); let isPalindrome = true; // 仅需循环半长即可完成校验,无需全量遍历 for (let i = 0; i < Math.floor(cleanStr.length / 2); i++) { if (cleanStr[i] !== cleanStr[cleanStr.length - 1 - i]) { isPalindrome = false; break; // 发现不对称直接跳出循环,减少不必要的计算 } } if (isPalindrome) { alert("是的,这是回文!"); } else { alert("不,这不是回文!"); } }
HTML代码
<!DOCTYPE HTML> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <title>回文检测</title> <script type="text/javascript" src="palindrome.js"></script> </head> <body> <div class="content"> <form> <input id="palind" type="text" placeholder="输入要检测的内容:" required> <p>这是回文吗?</p> <input id="clickme" type="button" value="点击检测" onclick="palindrome()" /> </form> </div> </body> </html>
CSS代码可保留原有内容不变
#palind { color: black; } #clickme { color: black; }
内容的提问来源于stack exchange,提问作者Breno Lira
相关产品推荐
相关产品推荐

