This only happens if your function addThisThingtoList()
is using asynchronous behavior (like Ajax calls) and thus its callback is called some time later after the for
loop has completely run its course and thus it's index value is at the ending value.
You can fix that with a closure that will freeze the loop value separately for each call to addThisThingtoList()
like this:
for (var j = 0 ; j < 30 ; j += 1) {
(function(index) {
addThisThingtoList(function () {
console.log( "item" + index);
});
})(j);
}
Working demo: http://jsfiddle.net/jfriend00/A5cJG/
By way of explanation, this is an IIFE (immediately invoked function expression). The variable j
is passed to the IIFE and it becomes a named argument to the function that I named index
. Then, inside that function, you can refer to index
as the value of j
that is frozen uniquely and separately for each call to addThisThingtoList()
. I could have named the argument index
to also be j
in which case it would have just overriden the higher scoped j
, but I prefer to use a separate variable name to be more clear about what is what.
Here's a good reference on the IIFE concept if you want to read more about it:
http://benalman.com/news/2010/11/immediately-invoked-function-expression/