Cannot read property 'length' of null (jav

2019-02-12 02:42发布

While trying to debug I am get the 'length' null error with this line. It is written just like the book instructed, so I don't understand why it is giving me the error? Thanks, =)

if (capital.length < 1) {

( here is the full code as requested.. 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> 

4条回答
三岁会撩人
2楼-- · 2019-02-12 03:10

The proper test is:

if (capital != null && capital.length < 1) {

This ensures that capital is always non null, when you perform the length check.

Also, as the comments suggest, capital is null because you never initialize it.

查看更多
唯我独甜
3楼-- · 2019-02-12 03:16

I tried this:

if(capital !== null){ 
//Capital has something 
}
查看更多
欢心
4楼-- · 2019-02-12 03:18
if (capital.touched && capital != undefined && capital.length < 1 ) { 
//capital does exists
}
查看更多
狗以群分
5楼-- · 2019-02-12 03:24

From the code that you have provided, not knowing the language that you are programming in. The variable capital is null. When you are trying to read the property length, the system cant as it is trying to deference a null variable. You need to define capital.

查看更多
登录 后发表回答