简体   繁体   English

如何将递增的值传递给回调

[英]how do I pass an incrementing value to a callback

I'm iterating over an array, and for each element, doing something that invokes a callback. 我正在遍历一个数组,并为每个元素做一些调用回调的操作。 My problem is that within the callback, I need to know which pass of the iteration it's at. 我的问题是在回调中,我需要知道迭代在哪一次进行。

Simplified, my code looks like this ... 简化,我的代码看起来像这样...

for (var i=0; i<3; i++ {
  setTimeout(function () {
      console.log(i);
  },1000);
}

And I'm wanting to see 我想看看

0
1
2

What I'm getting is 我得到的是

3
3
3

I understand why I'm getting 3's, but can't see how to get 0,1,2 我知道为什么我得到3,但是看不到如何得到0,1,2

NB. 注意 This is a simplified version of my problem. 这是我的问题的简化版本。 In myapp I'm actually calling a storage operation, so I can't simply provide "i" as an argument to the the callback function. 在myapp中,我实际上是在调用存储操作,因此不能简单地将“ i”作为回调函数的参数。

You need to capture the value at iteration time since JS has function scope so it's the same i that you reference.( and you don't want that. hence you need to create a closure. 你需要在迭代时间捕捉价值,因为JS具有的功能范围,以便它是相同的i ,你参考。(你不希望出现这种情况。因此你需要创建一个封闭。

for (var i = 0; i < 3; i++) {
    (function (a) {
        setTimeout(function () {
            console.log(a);
        }, 1000);
    })(i);
}

Why you are getting i as 3 is because settimeout is async, and both your forloop and set timeout function shares the same variable i . 为什么将i设为3是因为settimeout是异步的,并且forloop和set timeout函数都共享相同的变量i Which means your for loop runs completely before the callbacks are invoked where the i would have gone to 3 after all your iterations. 这意味着您的for循环完全在调用回调之前运行,在所有迭代之后i都将变为3 So your work around is to create a local scope for the variable or in otherwords create a closure. 因此,您的解决方法是为变量创建局部作用域,或者换句话说,创建闭包。

for (var i=0; i<3; i++) {
   (function(iter){ //Now with this you are creating a local closure for the variable iter and each setTimeout instance will no longer share the variable `i` instead it will use the variable created in its own scope defined by the anonymous function.
     setTimeout(function () {
         console.log(iter);
     },1000);
   })(i)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM