JavaScript…无法调用未定义的方法匹配

JavaScript…无法调用未定义的方法匹配,javascript,Javascript,我得到了这个错误:uncaughttypeerror:无法在我的JavaScript中调用未定义的的方法“match”。我尝试在没有jQuery的情况下编写这个,因为它将是站点上唯一的js 我的代码应该在 这是我的代码…(错误发生在第9行) (函数(窗口,文档,未定义){contentLoaded(窗口,函数)(){ var page=document.location.pathname.match(/[A-z]+$/)[0], nav_anchors=document.getElementsB

我得到了这个错误:
uncaughttypeerror:无法在我的JavaScript中调用未定义的
的方法“match”。我尝试在没有jQuery的情况下编写这个,因为它将是站点上唯一的js

我的代码应该在

这是我的代码…(错误发生在第9行)

(函数(窗口,文档,未定义){contentLoaded(窗口,函数)(){
var page=document.location.pathname.match(/[A-z]+$/)[0],
nav_anchors=document.getElementsByTagName('header')[0]
.getElementsByTagName('nav')[0]
.getElementsByTagName('a');
用于(导航锚中的i)

if(nav_锚定[i].href.match(/[A-z]+$/)[0]=page)//第9行
节点列表
具有
长度
名称项
属性

使用
for(var i=0;i
而不是
for i in foo
对它们进行迭代并只命中节点。

(函数(窗口,文档,未定义){contentLoaded(窗口,函数(){
(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(var i=0;i<nav_anchors.length;i++)
    if(typeof nav_anchors[i].href != "undefined" && nav_anchors[i].href.match(/[A-z]+$/)[0] == page)
      nav_anchors[i].classList.add('active');

})
})(this, this.document)
var page=document.location.pathname.match(/[A-z]+$/)[0], nav_anchors=document.getElementsByTagName('header')[0] .getElementsByTagName('nav')[0] .getElementsByTagName('a');
对于(var i=0;i
if(nav_锚[i].href.match(/[A-z]+$/)[0]=page)//第9行有时
document.location.pathname.match(/[A-z]+$/)
可以为null。如果尝试使用
document.location.pathname.match(/[A-z]+$/)[0]
则不能访问null的0元素。

不要使用
for(x in y)
浏览数组或节点列表。使用常规的
for(var i=0;i
循环。最好的方法是
for(var i=0,j=foo.length;i
这正进入可读性较差的微优化领域。除非出现性能问题,否则这样做毫无意义。谢谢!我没听清楚。也许这样更好?
document.location.toString().match(/[a-z\-\\\\\\\\\\\\\\\]+$/)[0]
使用类似这样的代码可能:
var page=document.location.pathname.match(/[a-z]+$/);如果(页面类型==“对象”)页面=页面[0];
(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(var i=0;i<nav_anchors.length;i++)
    if(typeof nav_anchors[i].href != "undefined" && nav_anchors[i].href.match(/[A-z]+$/)[0] == page)
      nav_anchors[i].classList.add('active');

})
})(this, this.document)
if(nav_anchors[i].href.match(/[A-z]+$/)[0] = page) //LINE 9 <-- Error