I am adding deferred getJSON calls to an array inside a for loop that reference local variables inside their success function. The problem I am having is that when the success function is called, the local variable is taking the value from the last iteration of the loop. See below example:
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/
This results in three alerts with the value 'c', whereas I would like the values 'a', 'b', and 'c'. Is this possible?
EDIT: The below works, but I'm not entirely sure why this differs?
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/