javascript - IE8 陷入数组推送的无限循环

标签 javascript

我对以下循环导致 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 中不起作用?

最佳答案

首先,切勿在数组上使用 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,.....]
    }
}

关于javascript - IE8 陷入数组推送的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10427440/

相关文章:

javascript - 如何在 javascript 中停止 window.setInterval?

javascript - 使用同一对象的其他属性初始化对象属性

javascript - 如何从使用 .find() 调用的对象中提取属性值?

javascript - 使用 Ajax 弹出窗口进行基本身份验证登录?

javascript - 使下拉菜单键盘和鼠标可浏览

javascript - 粗文本轮廓

javascript - 我只得到一次数据库输出,但没有再得到一次。为什么这不起作用?

javascript - ngView 不呈现模板

javascript - jqgrid 在编辑框中不正确选择下拉选项值

javascript - 比较没有时区的 JavaScript 日期