检查变量的长度时,Javascript“无法读取未定义的属性‘长度’”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17583366/
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
Javascript "Cannot read property 'length' of undefined" when checking a variable's length
提问by JVG
I'm building a node
scraper that uses cheerio
to parse the DOM
. This is more or a vanilla javascript question though. At one part of my scrape, I'm loading some content into a variable, then checking the variable's length
, like so:
我建立一个node
刮刀使用cheerio
解析DOM
。不过,这更像是一个普通的 javascript 问题。在我抓取的一部分中,我将一些内容加载到变量中,然后检查变量的length
,如下所示:
var theHref = $(obj.mainImg_select).attr('href');
if (theHref.length){
// do stuff
} else {
// do other stuff
}
This works just fine, until I came across a url for which $(obj.mainImg_select).attr('href')
didn't exist. I assumed that my theHref.length
check would account for this and skip through to the else: do other stuff
statement, but instead I got:
这工作得很好,直到我遇到一个$(obj.mainImg_select).attr('href')
不存在的网址。我以为我的theHref.length
支票会考虑到这一点并跳到else: do other stuff
声明,但我得到了:
TypeError: Cannot read property 'length' of undefined
TypeError: Cannot read property 'length' of undefined
What am I doing wrong here and how can I fix this?
我在这里做错了什么,我该如何解决?
回答by Paul S.
You can check that theHref
is defined by checking against undefined.
您可以theHref
通过检查undefined来检查是否已定义。
if (undefined !== theHref && theHref.length) {
// `theHref` is not undefined and has truthy property _length_
// do stuff
} else {
// do other stuff
}
If you want to also protect yourself against falsey values like null
then check theHref
is truthy, which is a little shorter
如果您还想保护自己免受错误值的影响,例如null
检查是否theHref
为真值,它会更短一些
if (theHref && theHref.length) {
// `theHref` is truthy and has truthy property _length_
}
回答by Benjamin Gruenbaum
Why?
为什么?
You asked whyit happens, let's see:
你问为什么会这样,让我们看看:
The official language specificaiondictates a call to the internal [[GetValue]]
method. Your .attr
returns undefined and you're trying to access its length.
该官方语言specificaion决定在内部调用[[GetValue]]
方法。您的.attr
返回未定义,并且您正在尝试访问其长度。
If Type(V) is not Reference, return V.
如果 Type(V) 不是 Reference,则返回 V。
This is true, since undefined is not a reference (alongside null, number, string and boolean)
这是真的,因为 undefined 不是引用(除了 null、数字、字符串和布尔值)
Let base be the result of calling GetBase(V).
令 base 为调用 GetBase(V) 的结果。
This gets the undefined
part of myVar.length
.
这得到了undefined
一部分myVar.length
。
If IsUnresolvableReference(V), throw a ReferenceError exception.
如果是 IsUnresolvableReference(V),则抛出一个 ReferenceError 异常。
This is not true, since it is resolvable and it resolves to undefined.
这不是真的,因为它是可解析的并且解析为未定义。
If IsPropertyReference(V), then
如果 IsPropertyReference(V),则
This happens since it's a property reference with the .
syntax.
发生这种情况是因为它是具有.
语法的属性引用。
Now it tries to convert undefined
to a function which results in a TypeError.
现在它尝试转换undefined
为导致 TypeError的函数。
回答by Tadeck
In addition to others' proposals, there is another option to handle that issue.
除了其他人的建议之外,还有另一种选择来处理这个问题。
If your application should behave the same in case of lack of "href
" attribute, as in case of it being empty, just replace this:
如果您的应用程序在缺少“ href
”属性的情况下应该表现相同,如在它为空的情况下,只需替换以下内容:
var theHref = $(obj.mainImg_select).attr('href');
with this:
有了这个:
var theHref = $(obj.mainImg_select).attr('href') || '';
which will treat empty string (''
) as the default, if the attribute has not been found.
''
如果未找到该属性,则将空字符串 ( ) 视为默认值。
But it really depends, on how you want to handle undefined "href
" attribute. This answer assumes you will want to handle it as if it was empty string.
但这实际上取决于您想如何处理未定义的“ href
”属性。此答案假定您希望将其视为空字符串来处理。
回答by JCOC611
There's a difference between an empty string ""
and an undefined variable. You should be checking whether or not theHref contains a defined string, rather than its lenght:
空字符串""
和未定义变量之间存在差异。您应该检查 theHref 是否包含定义的字符串,而不是它的长度:
if(theHref){
// ---
}
If you still want to check for the length, then do this:
如果您仍想检查长度,请执行以下操作:
if(theHref && theHref.length){
// ...
}
回答by Peter Alfvin
As has been discussed elsewhere, the .length
property reference is failing because theHref
is undefined. However, be aware of any solution which involves comparing theHref
to undefined
, which is not a keyword in JavaScript and can be redefined.
正如在别处讨论的那样,.length
属性引用失败是因为theHref
未定义。但是,要知道这涉及到比较任何解决方案theHref
来undefined
,这不是在JavaScript中的关键字,可以重新定义。
For a full discussion of checking for undefined variables, see Detecting an undefined object propertyand the first answer in particular.
有关检查未定义变量的完整讨论,请参阅检测未定义的对象属性,特别是第一个答案。
回答by AlliterativeAlice
If you aren't doing some kind of numeric comparison of the length property, it's better not to use it in the if statement, just do:
如果您没有对 length 属性进行某种数值比较,最好不要在 if 语句中使用它,只需执行以下操作:
if(theHref){
// do stuff
}else{
// do other stuff
}
An empty (or undefined, as it is in this case) string will evaluate to false (just like a length of zero would.)
空(或未定义,在本例中)字符串将评估为 false(就像长度为零一样。)
回答by Sundeep Pidugu
You can simply check whether the element length is undefined or not just by using
您可以简单地通过使用来检查元素长度是否未定义
var theHref = $(obj.mainImg_select).attr('href');
if (theHref){
//get the length here if the element is not undefined
elementLength = theHref.length
// do stuff
} else {
// do other stuff
}