window.prompt的值没有返回正确的"长度"适当的价值

时间:2017-04-20 01:24:54

标签: javascript html debugging

我对Javascript有点新意,我正在努力学习它。我目前正在创建一段代码,提示用户输入他们的名字,如果它有5个字符或更多,更少或更准确,则显示。但它一直向我显示它是5个字符,即使它超过5个。如果有人可以帮我调试这个,我将不胜感激。

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3school.org/1999/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8" />
        <title>Understanding Javascript</title>
    <script type="text/javascript"
            language="javascript">
    username = prompt("Please enter your name");
    message = "Hello," + username + " Your name has ";
    nameLen = username.Length;
    if (nameLen > 5)
        message = message + "more than ";
    else if (nameLen < 5)
        message = message + "less than ";
    else
        message = message + "exactly ";
    message = message + " 5 characters";

    alert(message)
    </script>
</head>
<body>
</body>
</html>

3 个答案:

答案 0 :(得分:1)

问题出在这一行:

nameLen = username.Length;

此行实际上将nameLen设为等于undefined

您设置if声明的方式

if (nameLen > 5) { // undefined is not greater than 5

} else if (nameLen < 5) { // undefined is not less than 5

} else { // undefined is not equal to 5 either, but who cares? it's a broad else

}

意味着它将始终进入else子句。

要解决此问题,只需将username.Length更改为username.length即可。 JavaScript是一种区分大小写的语言,因此如果您不小心,将来可能会出现这类错误。

答案 1 :(得分:0)

基本上,username.length应该修复它。房产名称中的错字。这段代码看起来很有效。

        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3school.org/1999/xhtml1-transitional.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <meta charset="utf-8" />
            <title>Understanding Javascript</title>
        <script type="text/javascript"
                language="javascript">
        username = prompt("Please enter your name");
        message = "Hello, " + username + " Your name has ";
        nameLen = username.length;
        if (nameLen > 5)
            message = message + "more than ";
        else if (nameLen < 5)
            message = message + "less than ";
        else {
            message = message + "exactly ";
            }
        message = message + " 5 characters";
  
        alert(message)
        </script>
    </head>
    <body>
    </body>
    </html>

答案 2 :(得分:0)

确切的语法:

  

nameLen = username.length;