回文字符串检测程序异常:无论输入是否为回文均返回True求助
Hey Sergio, I see exactly what's going on here! The issue boils down to when you're grabbing the input value from the text box.
The Root Cause
Right now, you're defining inputString in the global scope like this:
var inputString = document.getElementById("word").value;
This line runs the second your page finishes loading—and at that moment, the input box is empty (""). An empty string counts as a palindrome (it reads the same forwards and backwards), so every time you click the "Check!" button, your clickFunction is still using that original empty string instead of whatever you've typed into the box. That's why it always says the input is a palindrome!
The Fix
All you need to do is move the line that fetches the input value inside the clickFunction, so it grabs the current text in the box every time the button is clicked. Here's the corrected JavaScript code:
var textTrue = "It's a palindrome!"; var textFalse = "Sorry, that's not a palindrome."; //判断输入字符串是否为回文的函数,是则返回true,否则返回false function isPalindrome(inStr) { for (let i = 0; i < inStr.length; i += 1) { if (inStr[i] !== inStr[inStr.length - 1 - i]) { return false; } } return true; } /* 根据isPalindrome函数的返回结果输出对应提示的函数 */ function clickFunction() { // Grab the current input value WHEN THE BUTTON IS CLICKED var inputString = document.getElementById("word").value; if (isPalindrome(inputString)) { console.log(textTrue); } else { console.log(textFalse); } }
Your HTML doesn't need any changes—this tweak to the JavaScript will make the checker work exactly as you intended.
Optional Robustness Improvement (Nice-to-Have)
Right now, your checker is case-sensitive (e.g., "Racecar" would be marked as not a palindrome because "R" doesn't match "r") and doesn't handle spaces or punctuation. If you want to make it work with more real-world inputs, you can normalize the string before checking:
function clickFunction() { var inputString = document.getElementById("word").value; // Convert to lowercase and remove non-alphanumeric characters var normalizedStr = inputString.toLowerCase().replace(/[^a-z0-9]/g, ""); if (isPalindrome(normalizedStr)) { console.log(textTrue); } else { console.log(textFalse); } }
This way, phrases like "A man, a plan, a canal: Panama" will also be correctly identified as palindromes.
内容的提问来源于stack exchange,提问作者Sergio De Crescenzo

