【发布时间】:2016-11-17 06:22:20
【问题描述】:
我正在尝试将当前值传递给回调函数。我使用了this answers,但它对我不起作用。
for (var i = 0; i < 4; i++) {
(function(_i) {
var options = {
//Options here
};
console.log(_i); // 0, 1, 2, 3
LocalImageManager.download(options, function (results, _i) {
console.log(_i); //undefined, undefined, undefined, undefined
//Do stuff with results
});
}
})(i);
问题是函数总是与“i”变量一起工作,在循环结束后它是未定义的。
【问题讨论】:
-
在
download()周围使用 IIFE。LocalImageManager.download(options, function (results, _i) { (function (_i) { console.log(_i); //Do stuff with results })(i); }); -
_i将可供所有嵌套函数访问。您不需要将其作为参数传递。 -
您在
function (results, _i)中再次声明了_i,导致_i无法从循环中获取,请更改为function (results) -
@Liam - 看起来它已经关闭了。只是 OP 将 IIFE 的右括号放在了错误的位置。
-
是的,很明显@evolutionxbox 这有多个问题...