Creating an additional closure to store the current index and using that inside your actual function should do the trick, similar to this:
for (var i = 0; i < array.length; i++) {
$.getJSON("http://someapi", {
"one": two
}, (function () { // added closure...
var currentIndex = i; //...to allow declaration of additinal variables
return function (result) {
array[currentIndex].value = result.value; // use currentIndex here
};
})()); // () force immidiate execution
}
DEMO - Comparing results between not using a closure and using a closure
Open the DEMO and then click Run, watching the console outputs.
Code from DEMO:
var array = [1, 2, 3, 4, 5];
// Wihtout closure i is not always as expected.
for (var i = 0; i < array.length; i++) {
$.getJSON("#", {
"one": 1
}, function (result) {
console.log('no-closure: ' + i);
});
}
// With closure stored i (currenIndex) is in the expected order
for (var i = 0; i < array.length; i++) {
$.getJSON("#", {
"one": 1
}, (function () {
var currentIndex = i;
return function (result) {
console.log('closure: ' + currentIndex);
};
})());
}