Javascript 全局作用域的误解

标签 javascript variables scope

我经常遇到这个问题,我想我终于需要一个解释了。我有 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 通常会由事件处理程序调用并报告上述错误。

最佳答案

正如其他人所说,最好避免对数组使用 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 已经意味着“数组的第 i 个元素我的全局变量”

您只是将典型 for 循环的约定与 for... in 构造的约定混淆了。

关于Javascript 全局作用域的误解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16150448/

相关文章:

Javascript Electron/Monaco 编辑器无需对话框即可加载文件

javascript - 在 jQuery Mobile 中作为链接的选项值

javascript - ng-click、ng-mouseover 等是否会创建观察者并减慢页面速度?它比 jQuery 事件绑定(bind)更好吗?

使用变量的 PHP SQL 更新

C - 战列舰阵列

python - 一次设置多个对象属性

perl - Perl 中的 'my' 和 'our' 有什么区别?

c# - C# 中的 Foreach(currentScope 中的类变量)

javascript - 通过 mysql npm 包更新时出错

Ruby 打印当前可见性