Javascript “Cannot read property 'length' of undefined” when checking a variable's length

前端 未结 7 2059
孤独总比滥情好
孤独总比滥情好 2020-12-30 00:56

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

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-30 01:42

    Why?

    You asked why it happens, let's see:

    The official language specificaion dictates a call to the internal [[GetValue]] method. Your .attr returns undefined and you're trying to access its length.

    If Type(V) is not Reference, return V.

    This is true, since undefined is not a reference (alongside null, number, string and boolean)

    Let base be the result of calling GetBase(V).

    This gets the undefined part of myVar.length .

    If IsUnresolvableReference(V), throw a ReferenceError exception.

    This is not true, since it is resolvable and it resolves to undefined.

    If IsPropertyReference(V), then

    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.

提交回复
热议问题