javascript - Array in success function undefined -


why code

for(var = 0; < array.length; ++i) {     array[i]["bla"] = "check"; } 

work perfectly, whereas array here, according firebug, undefinied:

for(var = 0; < array.length; ++i) {     $.ajax({         type: "post",         url: "my url",         data: "data here",         success: function() {             array[i]["bla"] = "check";         }     }); } 

how can fix issue?

due how closures work, value of i going equal array.length in callback, because that's equals after loop done (after all, i < array.length false). , position undefined. need re-bind i inside loop make current value "stick". unfortunately way in standard js use yet function, instance:

for (...; i++) {     (function(boundi) {         // boundi bound current value of in current scope         // if want, can call boundi "i", make sure understand         // how scopes work in js before do.         $.ajax({             ...             success: function() {                 array[boundi]["bla"] = "check";             }         });     })(i); // pass in current value of loop index gets bound boundi } 

Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -