简体   繁体   English

循环怪异行为的Javascript

[英]Javascript for loop weird behavior

I find it weird that I get this output: 我得到以下输出结果很奇怪:

Wait..
Request 2 Complete.
Request 2 Complete.

On a simple for loop: 在简单的for循环中:

for (var i = 0, j = urls.length; i < j; i += 1) {
    $.ajax({
        url: urls[i],
        dataType: 'jsonp',
        complete: function() {
            log.append('Request ' + i + ' Complete.' + "\n");
            if (i == (j - 1)) {
                log.append('Done.');
            }
        }
    });

}

How come i is always equal to 2 ? 为什么i总是等于2

This is, because both calls to i inside your ajax request reference the same i of the for -loop. 这是因为在ajax请求中对i两次调用都引用了for -loop的相同i At the point in time, when the requests are completed (and thus i is accessed) the loop has terminated and i has the final value, here 2 . 在时间点上,当请求完成时(因此可以访问i ),循环已终止,并且i具有最终值,此处为2

I think you look for something like this: 我认为您正在寻找这样的东西:

for (var i = 0, j = urls.length; i < j; i += 1) {
  !function( i ){
    $.ajax({
        url: urls[i],
        dataType: 'jsonp',
        complete: function() {
            log.append('Request ' + i + ' Complete.' + "\n");
            if (i == (j - 1)) {
                log.append('Done.');
            }
        }
    });
  }( i );
}

By passing the value of i to the immediately executed function, you create a copy of the respective value of i to use inside the ajax-requests. 通过将i的值传递给立即执行的函数,可以创建i的各个值的副本以在ajax请求内使用。

try using 尝试使用

     async = false;
in ajax request

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM