【问题标题】:IE8 gets caught in an infinite loop with array pushIE8 陷入数组推送的无限循环
【发布时间】:2012-05-03 08:06:58
【问题描述】:

我对导致 IE8 中的无限循环的以下循环感到困惑

for (var i in theArray) {
            this.theArray.push(theArray[i]);
}

IE8 陷入无限循环,我不明白为什么,因为 this.theArray 是一个全局数组,而 theArray 是一个局部变量。

如果我有类似以下的情况,我会理解会发生无限循环:

for (var i in theArray) {
            theArray.push(theArray[i]);
}

这只发生在 IE8 中。 IE8 对变量和作用域的处理方式不同吗?

编辑

这是我在一个对象中的内容

this.theArray = new Array();

this.selection = function(theArray) {
    for (var i in theArray) {
        this.theArray.push(theArray[i]);
    }
}

编辑

我发现我将全局变量作为参数传递给函数。呸!为什么这在 IE8 中不起作用?

【问题讨论】:

  • 这段代码在哪里运行?在全球范围内?
  • 为什么不改本地var的名字??????
  • 我们能看到整个代码吗?或者至少是我们可以测试的精简版本。另外,其他浏览器的控制台说什么?当循环无限时,其他浏览器有一个内部“断路器”。
  • 我已经添加了我正在使用的代码。

标签: javascript


【解决方案1】:

首先,永远不要在数组上使用for in 循环。它将遍历值以及增强的属性。

那么,this 无法在您的代码中确定。 this 可能指的是全局对象。此外,您可能错过了在局部变量中使用 var,从而使 theArray 指向您要附加到的同一个全局 theArray

var theArray = [1,2,3];

function foo(){
    theArray = [4,5,6]; //missing var, theArray is the global theArray
    for (var i in theArray) {
        //you are pushing to the same array you are fetching from
        this.theArray.push(theArray[i]);

        //[4,5,6,4,5,6,4,5,6,.....]
    }
}

【讨论】:

    【解决方案2】:

    您应该尝试self 而不是this

    self 是脚本运行所在的窗口或框架,因此就像访问全局变量一样。

    for (var i in theArray) {
        self.theArray.push(theArray[i]);
    }
    

    如果这没有帮助,请为数组指定不同的变量名称。

    或者:你确定theArray 是本地范围的吗?在定义 `theArray?

    var theArray
    

    【讨论】:

    • window.theArray 更容易理解
    • @RobW 经过一番研究,我删除了我的评论
    【解决方案3】:

    按照我的阅读方式,它应该进入一个无限循环。您正在枚举一个数组并同时向其中添加项目,即:

    读取索引 i,创建 i+1,重复。

    当您修改您正在枚举的集合时,其他语言会崩溃,这会给您一个错误指示。

    我很惊讶它只在 IE8 中失败。我是否误读了您的代码 sn-p?

    【讨论】:

      猜你喜欢
      • 2020-05-13
      • 1970-01-01
      • 1970-01-01
      • 2013-03-17
      • 2021-02-15
      • 2022-01-23
      相关资源
      最近更新 更多