1

我经常遇到这个问题,并认为我最终会要求解释。我有 Google Chrome 并经常使用 javascript 控制台。当我声明一个全局变量时,我总是可以在控制台中访问它的内容,但是当我在浏览器中运行脚本时尝试从函数内部访问变量时,我经常会收到“无法读取未定义的属性'top'”类型错误.

我将在此处粘贴一段代码,如果有人可以向我解释为什么会出现此错误,我将非常感激!

// JavaScript Document
var myglobalvariable;
// ...

$(document).ready( function() {
  myglobalvariable = document.getElementsByTagName("article");
  // ...
});

function myFunction() {
  for (i in myglobalvariable) {
    mylocalvariable_top = myglobalvariable[i].style.top; // Error points to this line
  // ...
  }
}

然后 myFunction 通常会被事件处理程序调用并报告上述错误。

4

3 回答 3

1

正如其他人所说,最好避免for ... in使用数组。也就是说,为了澄清导致此错误的误解,您应该编写:

function myFunction() {
  for (i in myglobalvariable) {
    mylocalvariable_top = i.style.top; // <-- i IS the element
                                       // <-- for clarity you should probably rename "i" to
                                       //    "element" or something more descriptive which will
                                       //      make clear it is not a numerical index
  // ...
  }
}

也就是说,进行查找没有意义,myglobalvariable[i]因为在您的情况下i已经意味着“数组 myglobalvariable 的第 i 个元素”

您只是将典型for循环的约定与for... in构造的约定混为一谈。

于 2013-04-22T15:18:19.093 回答
0

我怀疑你正在做的不是你想要的。

for (i in myglobalvariable) { }

这不会遍历数组中的项目,而是遍历对象的键/属性名称。

myglobalvariable[i]

在上面,您可以访问使用该键键入的属性。

myglobalvariable[i].style.top

在上面,您可以访问所述对象的样式属性。如果该对象没有样式属性,那么这将是未定义的。这意味着当您在不存在的属性上调用 .top 时,您会得到“无法读取未定义的属性 'top'”。

您在这里提出的是一个具体问题,而不是一般的“全球范围误解”。

解决方案

var i, len = myglobalvariable.length;
for (i = 0; i < len; i++) {
    if (myglobalvariable[i].style)
        mylocalvariable_top = myglobalvariable[i].style.top;
  // ...
}
于 2013-04-22T15:11:17.913 回答
0

这将创建一个NodeList节点。

$(document).ready( function() {
  myglobalvariable = document.getElementsByTagName("article");
  // ...
});

这将遍历每个节点对象上的任何附加属性NodeList

function myFunction() {
  for (i in myglobalvariable) {
    mylocalvariable_top = myglobalvariable[i].style.top; // Error points to this line
  // ...
  }
}

也就是说,您可能会遇到myglobalvariable不是节点且没有style属性的项目。特别是,将i在迭代期间的某个时间点。itemlength

这将更安全地遍历列表:

function myFunction() {
  for (var i = 0; i < myglobalvariable.length; i++) {
    mylocalvariable_top = myglobalvariable[i].style.top; // Error points to this line
  // ...
  }
}
于 2013-04-22T15:13:25.050 回答