如何创建一个接受输入的函数并测试它是否是回文

How to to create a function that will take an input and test if it's a palindrome or not?

本文关键字:函数 测试 回文 是否是 输入 创建 何创建 一个      更新时间:2023-09-26

这是我现在写的函数。Web 控制台对我没有多大作用。每次在文本框中输入单词时,即使它是回文,也只是返回"undefinedThis is not a palindrome!"

不知道这里出了什么问题。也许与if声明有关?如何使函数忽略大写字母?我希望它既考虑"bob",又"Bob"回文。

function test() {
    // Assumes: a string is entered into the "palin" text box
    // Results: tests if the string is a palindrome and
    // returns the conclusion to outputDiv
    var word, copy, i;
    word = document.getElementById("palin").value;
    copy = " ";
    i = 0;
    while (i < word.length) {
        copy = word.charAt(i) + copy;
        i=i+1;
    }
    if (word === copy) {
        document.getElementById("outputDiv").innerHTML =
            document.getElementById("outputDiv").value +
            "This is a palindrome!";
    } else {
        document.getElementById('outputDiv').innerHTML =
            document.getElementById('outputDiv').value +
            "This is not a palindrome!";
    }
}

最好将逻辑与演示文稿分开。在您的情况下,逻辑是回文检查。演示文稿正在从文本框获取输入并将输出发送到div。

这就是我要做的:

var input = document.getElementById("input");
var output = document.getElementById("output");
document.getElementById("button").addEventListener("click", function () {
    var s = input.value;
    output.innerHTML = s + " is" + (isPalindrome(s) ? "" : " not")
                     + " a palindrome.";
});
function isPalindrome(s) {
    s = s.toLowerCase();
    return s.split("").reverse().join("") === s;
}
<input type="text" id="input"/>
<button id="button">Palindrome?</button>
<div id="output"></div>

如您所见,我已将isPalindrome逻辑放入一个单独的函数中。因此,我将逻辑与演示文稿分开。您应该始终这样做。它使编程变得更加简单。

你的代码几乎是正确的,这是固定的JSFIDDLE示例

将您的代码更改为

function test() {
    var word, copy, i;
    word = document.getElementById("palin").value.toLowerCase();//turn to lowercase
    copy = "";
    i = 0;
    while (i < word.length) {
        copy = word.charAt(i) + copy;
        i=i+1;
    }
    if (word === copy) {
        document.getElementById("outputDiv").innerHTML =
            document.getElementById("palin").value + " This is a palindrome!";
    } else {
        document.getElementById('outputDiv').innerHTML =
            document.getElementById('palin').value + " This is not a palindrome!";
    }
}

copy = " ";应该更改为copy = "";这是第一个问题,因为"bob" not equal to "bob "你使用了未定义document.getElementById("outputDiv").value,因为它是一个div而不是文本区域,所以值是未定义的,你可能需要的是document.getElementById("palin").value