How to pass values to a callback function at the time of the request call?

后端 未结 3 1160
执念已碎
执念已碎 2021-01-07 08:32

I have the following situation:

var foo = [ 0, 1, 2 ]
for (var i in foo) {
    Asyncstuff.get(URI).on(\'response\', function(res) { console.log(i); } });
}
<         


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-07 09:14

    As cwolves has mentioned you need to wrap it using closure. The reason for that is in JavaScript and some other languages (ex: C#) closure capture "variables" and not "values" hence in your code the variable "i" is captured by the inner function and when that function executes it uses the captured variable "i" which obviously will be last value in the loop as the loop ends. You need to be careful when you use closures in languages such as JavaScript which captures variables.

    In cwolves solution the "i" inside the function becomes a new variable and is not same as the I in the for loop and hence it works fine.

提交回复
热议问题