我将延迟的getJSON调用添加到for循环中的一个数组中,该循环引用其成功函数中的局部变量。我遇到的问题是,当调用success函数时,局部变量将从循环的最后一次迭代中获取值。见下面的例子:
var calls = [];
var arr = ['a','b','c'];
for (var a in arr) {
calls.push(
$.getJSON(window.location, function() { alert(arr[a]); })
);
}
$.when.apply($,calls);
jsFiddle:http://jsfiddle.net/Me5rV/
这导致三个警报值为'c',而我想要值'a','b'和'c'。这可能吗?
编辑:以下是有效的,但我不完全确定为什么会有所不同?
var calls = [];
var arr = ['a','b','c'];
for (var a in arr) {
calls.push(
$.getJSON(window.location, function(x) {
alert(x);
}(arr[a]))
);
}
$.when.apply($,calls);
jsFiddle:http://jsfiddle.net/Me5rV/1/
答案 0 :(得分:1)
回顾一下这样的循环:
var a = [];
for( var i = 0; i < 3; ++i ) {
a.push( function() {
alert(i);
});
}
实际上是这样做的:
var a = [], i = 0;
a.push( function(){
alert(i);
});
i++;
a.push( function() {
alert(i);
});
i++;
a.push( function() {
alert(i);
});
i++;
//condition isn't met, loop terminates
alert(i) //alerts 3 because i is 3 now.
//That's why all the functions alert 3, because they all
//refer to this i and its value is 3
现在你可以这样做(重复删除):
a.push( function(i){
return function() {
alert(i); //Refers to the i passed as argument to the outer function
//not the global one
//The local i has whatever value the global i had when it was passed
//as argument
};
}(i));