JavaScript ...无法调用undefined的方法匹配

jar*_*ack 2 javascript

我收到此错误:Uncaught TypeError: Cannot call method 'match' of undefined在我的JavaScript中.我试图在没有jQuery的情况下写这个,因为它将是网站上唯一的js.

我的代码应该<a href="...>在链接到当前页面的导航中添加一个类"active" .

我猜它可能是contentLoaded函数?.... 来源

这是我的代码......(错误发生在第9行)... 小提琴

(function(window, document, undefined) { contentLoaded(window, function() {

  var page = document.location.pathname.match(/[A-z]+$/)[0],
      nav_anchors = document.getElementsByTagName('header')[0]
                            .getElementsByTagName('nav')[0]
                            .getElementsByTagName('a');

  for(i in nav_anchors)
    if(nav_anchors[i].href.match(/[A-z]+$/)[0] = page) //LINE 9 <-- Error
      nav_anchors[i].classList.add('active');

})
})(this, this.document)
Run Code Online (Sandbox Code Playgroud)

谢谢!

Que*_*tin 5

NodeListslength,item而且namedItem性质.

用于for (var i = 0; i < foo.length; i++)for i in foo迭代它们而只是命中节点.

  • 这正在进入不太可读的微观优化的土地.除非出现性能问题,否则没有意义. (2认同)