无法读取属性'length'的null(javascript)

JBS*_*MOM 15 javascript null

在尝试调试时,我得到此行的'length'null错误.它写的就像书中指示的那样,所以我不明白为什么它会给我错误?谢谢,=)

if (capital.length < 1) {
Run Code Online (Sandbox Code Playgroud)

(这是所要求的完整代码.. SORRY)

<script type="text/javascript">
var capital = window.prompt("What is the capital of Missouri?","")

if (capital.length < 1) {
    document.getElementById("firstdiv").innerHTML="Sorry you don't feel like playing.<br /> The Capital of Missouri is Jefferson City.";
}
else {
    if (!window.confirm("Is that your final answer?")){ return true;

        document.getElementById("firstdiv").innerHTML = "The capital of Missouri is: <bold>" + capital + "</bold>, so says you.";
    }
    else{
        return false;
    }
}
</script> 
Run Code Online (Sandbox Code Playgroud)

Hun*_*len 48

适当的测试是:

if (capital != null && capital.length < 1) {
Run Code Online (Sandbox Code Playgroud)

这保证了capital永远不空,当您执行长度检查.

此外,正如评论所示,capitalnull因为您从未初始化它.

  • 我现在可能会将其写为“if (capital &amp;&amp; Capital.length &lt; 1)”,而不是明确引用“null”。 (3认同)