I\'m having some difficulty with an array that is (outside of an asynchronous call) perfectly well-defined but when I call its indices inside an asynch request (e.g. $.getJS
The problem is that the callback function happens some time later when the ajax function completes. By then, the array index has advanced to the end of your for
loop (thus it points off the end of the array) to an undefined value. The array is still there, but your index has been changed by the time the completion function is called.
The technique usually used to get the index into the success handler is to capture it in a function closure where it gets captured for use in the completion function.
You can create a closure that captures the index value by replacing your success handler with this:
(function(index) {
return function(dataJSON2) {
resultArray = dataJSON2['data'];
resultJSON += friendArray[index] + ":" + resultArray.length + ",";
//alert(resultJSON);
}
}) (i);
This outer function executes and creates a closure which captures the value of i and uniquely makes it available to the success handler. When it self executes, it returns your success handler which is thus passed to the getJSON function to be called later. But, when it is called later the value of i
that you need is available to the success handler via the argument in the self executing function.
Here's another way to think about closures used with callbacks.
Here's an example of that:
function cycleOnOff(sel, cnt, delay) {
var obj = $(sel);
function next() {
if (cnt-- > 0) {
obj.toggle();
setTimeout(next, delay);
}
}
next();
}
In this case, the function next()
is a callback to setTimeout()
, but that function has full access to the variables within its parent scope: sel
, cnt
, delay
and obj
.