JavaScript if / else问题:由于区分大小写,“是”被视为“否”

时间:2014-01-17 18:59:14

标签: javascript if-statement

我是学习JS的新手,我写了我自己的一个练习版本,试图记住我学到的东西。这是我写的:

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>

<script>

alert("Good morning!");
var hire = prompt("Are you here because you're interested in hiring me?");

if (hire === "yes") {
    alert("You've just made my day. Carry on.")
}

else {
    alert("Well, I hope you're at least thinking about it.")
}

</script>

</body>
</html>

问题是,如果你没有在所有小写字母中输入'yes',它会假定答案属于'else'类别并吐出错误的答案。我一直在阅读有关将其转换为大写的方法,但我仍然无法弄清楚它需要什么额外的代码。感谢。

2 个答案:

答案 0 :(得分:2)

您应该使用.toLowerCase()来强制他们的回复为小写。然后你可以检查它总是小写。

if (hire.toLowerCase() === 'yes') {
    alert('You\'ve just made my day. Carry on.');
} else {
    alert('Well, I hope you\'re at least thinking about it.');
}

答案 1 :(得分:0)

这没关系

    <!DOCTYPE html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    </head>

    <body>

    <script>

    alert("Good morning!");
    var hire = prompt("Are you here because you're interested in hiring me?");

    if (hire.toLowerCase() === "yes") {
        alert("You've just made my day. Carry on.")
    }

    else {
        alert("Well, I hope you're at least thinking about it.")
    }

    </script>

    </body>
    </html>