Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 检查回文程序是否总是返回True_Javascript - Fatal编程技术网

Javascript 检查回文程序是否总是返回True

Javascript 检查回文程序是否总是返回True,javascript,Javascript,很抱歉,格式不好。我写了这个回文检查程序,不明白为什么它总是返回true。“单词”是指通过html获取的信息,“reportIfPalindrome”也是如此。值被导入并显示,所以html没有问题。谢谢你的帮助 const wordBox = document.getElementById('word'); wordBox.addEventListener('input', checkIfPalindrome); function checkIfPalindrome() { con

很抱歉,格式不好。我写了这个回文检查程序,不明白为什么它总是返回true。“单词”是指通过html获取的信息,“reportIfPalindrome”也是如此。值被导入并显示,所以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;

}
const wordBox=document.getElementById('word');
addEventListener('input',checkIfPalindrome);
函数checkIfPalindrome(){
const word=wordBox.value;
const allCaps=word==word.toUpperCase();
const outsideTrim=allCaps==word.trim();
让我们完全地把它加上“”;
让个性=”;
对于(x=0;x=0;x--){
反向限制=完全限制的子串(x,x+1);
}   
让结果=完全终止===反向终止;
document.getElementById('reportIfPalindrome')。innerHTML=result;
}

您的代码中有很多缺陷。首先,您正在存储变量的布尔值,您似乎打算在其中存储大写和修剪的单词。其次,您没有使用正确的边界条件运行循环。请参阅下面更新的代码段

checkIfPalindrome();
函数checkIfPalindrome(){
const word=“aBa”;
const allCaps=word.toUpperCase();
const outsideTrim=allCaps.trim();
让我们完全地把它加上“”;
让个性=”;
对于(x=0;x=0;x--){
反向限制=反向限制+完全限制子串(x,x+1);
}   
让结果=完全终止===反向终止;
//document.getElementById('reportIfPalindrome')。innerHTML=result;
控制台日志(结果);

}
你经常这样做
const allCaps=word===word.toUpperCase(),它测试右侧的相等性,然后将其分配给您的变量。您的许多变量最终都是布尔值。我肯定这不是你想要的。另外,你的函数实际上并没有返回任何东西。我使用你的建议来实现它。非常感谢。:)