无法读取属性'length'的null(javascript) [英] Cannot read property 'length' of null (javascript)

查看:506
本文介绍了无法读取属性'length'的null(javascript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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


推荐答案

正确的测试是:

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

当您执行长度检查时,这确保 capital 始终非空。

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

此外,正如评论所示,资本 null 因为你从未初始化它。

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

这篇关于无法读取属性'length'的null(javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆