【问题标题】:Allowing both lower and uppercase when doing quiz application in JavaScript?在 JavaScript 中进行测验应用程序时允许小写和大写?
【发布时间】:2014-02-08 06:18:03
【问题描述】:

我目前正在用 JavaScript 进行测验,希望用户可以使用小写或大写进行输入,但不会影响结果。我已经看过了,但我很难看到任何可以提供帮助的东西。 (我知道要添加一个问题,当然还有正确的答案——我目前正在开发)。谢谢。

function Quiz()
{
    var answer = prompt("question here?","");
    if (answer=="your answer here")
    {
    alert ("Correct!");
    }
    else 
    alert ("Incorrect");
}

【问题讨论】:

标签: javascript alert uppercase lowercase


【解决方案1】:

您可以使用String.prototy.toLowerCase() 函数将两边转换为小写。这将确保两个字符串都是小写的。

function Quiz()
{
    var answer = prompt("question here?","");
    if (answer.toLowerCase()=="your answer here".toLowerCase())
    {
    alert ("Correct!");
    }
    else 
    alert ("Incorrect");
}

【讨论】:

    【解决方案2】:

    您想在answer 上致电String.prototype.toLowerCase。这会将所有内容转换为小写字母,以便您轻松比较:

    if (answer.toLowerCase().trim() == "your answer here".toLowerCase()) {
        // ...
    }
    

    trim 函数会删除尾随和前导空格,以防用户意外输入。

    【讨论】:

    • 但是当右侧包含一些大写字母时会发生什么?你的比较总是会失败,在这种情况下你应该转换双方
    • 绝对有效的观点,我承认我只是复制了答案的字符串,发现它是小写的,所以不需要显式转换它。当然,如果你有任何变量,你也必须转换它。
    猜你喜欢
    • 1970-01-01
    • 2021-08-31
    • 2014-06-18
    • 2020-12-22
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    相关资源
    最近更新 更多