抱歉笨拙的格式化。我写了这个回文检查程序,无法弄清楚为什么它总是返回true。 '单词'指的是通过html的摄取,并且报告ifIfPalindrome'。值被吸收并显示,因此html没有问题。任何帮助表示赞赏
const wordBox = document.getElementById('word');
wordBox.addEventListener('input', checkIfPalindrome);
function checkIfPalindrome() {
const word = wordBox.value;
const allCaps = word === word.toUpperCase();
const outsideTrim = allCaps === word.trim();
let completelyTrimmed = "";
let individualCharacter = "";
for(x=0; x<outsideTrim.length; x++)
{
individualCharacter = outsideTrim.substring(x, x+1)
completelyTrimmed+= individualCharacter === " "? "": individualCharacter;
}
let reverseString = ""
for (x=completelyTrimmed.length-1; x>=0; x--){
reverseString = completelyTrimmed.substring(x, x+1);
}
let result = completelyTrimmed===reverseString;
document.getElementById('reportIfPalindrome').innerHTML = result;
}
答案 0 :(得分:1)
您的代码中存在相当多的缺陷。首先,您正在为您看似打算存储大写和修剪单词的变量存储布尔值。其次,您没有使用正确的边界条件运行循环。请参阅下面的更新代码段。
checkIfPalindrome();
function checkIfPalindrome() {
const word = "aBa";
const allCaps = word.toUpperCase();
const outsideTrim = allCaps.trim();
let completelyTrimmed = "";
let individualCharacter = "";
for(x=0; x<outsideTrim.length; x++)
{
individualCharacter = outsideTrim.substring(x, x+1)
completelyTrimmed+= individualCharacter === " "? "": individualCharacter;
}
let reverseString = ""
for (x=completelyTrimmed.length-1; x>=0; x--){
reverseString = reverseString + completelyTrimmed.substring(x, x+1);
}
let result = completelyTrimmed===reverseString;
//document.getElementById('reportIfPalindrome').innerHTML = result;
console.log(result);
}
&#13;