索引为"for".在"setInterval"内部 [英] Index of "for" inside "setInterval"
问题描述
我有一个对象,并将其放入一个数组中,并使用 for
迭代该数组,对于数组中的每个对象,我都设置了一个设置间隔,以使用一个参数,但我不能.这是我的班级".
I have an object and i put it in a Array, and the i iterate the array with for
and for each object in the array i put a set interval for calling a method of the object with a parameter, but i cant.
This is my "Class".
function ClassTest() {
this.test = function(word) {
console.log(word);
}
}
我创建对象并将其放在数组上:
The i create the object and put it on a Array:
var array = [];
var objectTest = new ClassTest();
array.push(objectTest);
当我设置时间间隔时:
for(var i = 0; i < array.length; i++) {
array[i].loop = setInterval(function() {
array[i].test("hello")
}, 1000);
}
问题是setInterval函数主体中的var i
存在,我可以创建一个var index
并且存在,但是我不明白为什么 index
存在,而var i
不存在:
The problem is that the var i
in the setInterval function dosent exist, i can create a var index
and the it exist but i dont understand why index
exist and the var i
not.:
for(var i = 0; i < array.length; i++) {
var index = i;
array[i].loop = setInterval(function() {
array[index].test("hello")
}, 1000);
}
当我不使用 index
var时,会出现此错误:
I get this error when i dont use the index
var:
Uncaught TypeError: Cannot read property 'test' of undefined
推荐答案
因为您的 for
循环会立即执行.到您的 setInterval()
首次执行时,您的 for
循环将持续很长时间,并且您的 i
将不在数组范围.
Because your for
loop executes immediately. By the time your setInterval()
executes for the first time, your for
loop will have long since finished and your i
will be outside of the range of your array.
在此示例中,我们的 array
的 length
为3.当我们的 for
循环结束时,我们的 i
变量将等于 3
.如果我们在 setTimeout
:
In this example, our array
has a length
of 3. When our for
loop finishes, our i
variable will be equal to 3
. The number 3
will be displayed three times in our JavaScript console if we log i
within the setTimeout
:
var array = [1, 2, 3];
for (var i = 0; i < array.length; i++) {
setTimeout(function() {
console.log(i);
}, 1000);
}
这篇关于索引为"for".在"setInterval"内部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!