无法读取property 'length'null (javascript)

Cannot read property 'length' of null (javascript)

本文关键字:javascript null length 读取 property      更新时间:2023-09-26

在尝试调试时,我得到了这一行的'长度' null错误。它是按照书上的指示写的,所以我不明白为什么它会给我错误?谢谢,=)

if (capital.length < 1) {

(这里是请求的完整代码…抱歉)

<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> 

正确的测试是:

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

这确保capital在执行长度检查时始终非null。

此外,正如注释所建议的,capitalnull,因为您从未初始化它。

如果定义了大写,这也可以——求值。如果没有,这意味着大写未定义或为null(或其他值,在js中计算为false)

if (capital && capital.length < 1) {do your stuff}

从您提供的代码中,不知道您正在使用的编程语言。变量capital为空。当您试图读取属性长度时,系统无法读取null变量。您需要定义capital

if (capital.touched && capital != undefined && capital.length < 1 ) { 
//capital does exists
}

我试过了:

if(capital !== null){ 
//Capital has something 
}

Use Try cache

尝试{

//你的代码

}抓住(err) {

console.log (err)

}