我如何将索引器从外部 for 循环传递到该 for 循环内的回调函数中。我的函数是 client.get() (请参阅我的代码以获取所需的输出)。
some_array = ['a', 'b', 'c'];
for(var i = 0; i < some_array.length; i++){
console.log(some_array[i]); // This prints a, b, c as expected
client.get("http://foo/" + some_array[i] + "/bar", function (data, response) {
console.log(some_array[i]); // THE PROBLEM: This prints undefind, I need it to print the exact same as the first console.log() statement
console.log(i); // This also prints undefined
console.log(some_array); // This prints ['a', 'b', 'c']
}
}
由于 some_array 是全局的,我可以在回调中很好地打印它,但是,我无法访问 some_array 中的任何元素,我该怎么做?
最佳答案
最简单的方法是使用let
而不是增量变量 var ..
for(let i = 0; i < some_array.length; i++){
/// code here...
}
由于 let
是 block 作用域,因此它在 block 中的任何位置都是相同的,即使在异步函数的回调中也是如此。
这是一个使用异步函数循环的示例,以演示差异。
var a = [1,2,3,4];
for(let i=0; i<a.length; i++){
setTimeout(function(){
console.log("Using let", a[i]);
}, 50);
}
for(var i=0; i<a.length; i++){
setTimeout(function(){
console.log("Using var", a[i]);
}, 50);
}
关于javascript - 将索引器传递到回调中的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48918696/