我对以下循环导致 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/