无法读取 null 的属性“长度”(javascript)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15731559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot read property 'length' of null (javascript)
提问by JBSAMOM
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>
回答by Hunter McMillen
The proper test is:
正确的测试是:
if (capital != null && capital.length < 1) {
This ensures that capital
is alwaysnon null, when you perform the length check.
这保证了capital
是永远不空,当您执行长度检查。
Also, as the comments suggest, capital
is null
because you never initialize it.
此外,正如评论所暗示的那样,capital
是null
因为您从未初始化它。
回答by secretformula
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
.
根据您提供的代码,不知道您正在编程的语言。变量capital
为空。当您尝试读取属性长度时,系统不能,因为它正在尝试遵循空变量。您需要定义capital
.
回答by Naramsim
if (capital.touched && capital != undefined && capital.length < 1 ) {
//capital does exists
}
回答by Aldo Geovani
I tried this:
我试过这个:
if(capital !== null){
//Capital has something
}
回答by Kamil Naja
This also works - evaluate, if capital is defined. If not, this means, that capital is undefined or null (or other value, that evaluates to false in js)
这也有效 - 如果定义了资本,则进行评估。如果不是,这意味着该大写是未定义的或为空的(或其他值,在 js 中计算为 false)
if (capital && capital.length < 1) {do your stuff}