scope of variables in JavaScript callback functions

前端 未结 5 920
野的像风
野的像风 2020-12-01 06:51

I expected the code below to alert \"0\" and \"1\", but it alert \"2\" twice. I don\'t understand the reason. Don\'t know if it is a problem of jQuery. Also, please help me

5条回答
  •  伪装坚强ぢ
    2020-12-01 07:20

    What's occurring here is your AJAX request $.get is completing after the loop has completed. Because of this, i ends up being the final variable it's set to when the iterations complete, being 2. This is just a weird JavaScript gotcha, and has nothing to do with jQuery.

    One thing you can do is queue up these calls asynchronously so that iteration halts until the current AJAX request completes. If you don't want to do that, you can capture the variable i in a function closure in each iteration.

    Something like this:

    for ( var i = 0; i < 2; i++ )
        (function(iter){
            $.get('http://www.google.com/', function(){
                alert( iter );
            });
        })(i); // Capture i
    

提交回复
热议问题