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

前端 未结 7 2002
孤独总比滥情好
孤独总比滥情好 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:45

    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:

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

    0 讨论(0)
提交回复
热议问题