首页 > 解决方案 > For 循环变量自动递增

问题描述

我创建了一个 for 循环并在其中运行 Javascript(jquery) 代码。但不知何故,for循环变量会自动递增。

for (var i=0; i<len; i++) {    //len=2
        console.log(i);  // outputs 0 and 1 as expected 
        $.ajax({
        url:'execute.php',
        method:'GET',
        data:{
            link: items[i]
        },

        success:function(data){
            console.log(i);       //outputs 2 and 2. It sould be 0 and 1
            $("#div1").html(data);
            var item = $(".sticky-item-title .title").html();
            $("#product-"+ i).html(item);
        },
        error:function(data){
            alert('error' + data);
        }
    });
}

$.ajax 之前的 console.log 按预期显示 0 和 1(我在 len 中有 2 个项目)。但是成功函数中的console.log显示为2和2。为什么以及在哪里增加。我试过这段代码

for (var i=0; i<len; i++) {
        var s=i;
        $.ajax({
        url:'execute.php',
        method:'GET',
        data:{
            link: items[s]
        },

        success:function(data){
            console.log(s);          //outputs 1 and 1. It should be 0 and 1 
            $("#div1").html(data);
            var item = $(".sticky-item-title .title").html();
            $("#product-"+ s).html(item);
        },
        error:function(data){
            alert('error' + data);
        }
    });
}

这里变量 s 显示 1 和 1 而不是 0 和 1。

我在这里做错了什么。提前致谢

标签: javascriptjqueryfor-loop

解决方案


当你var用来定义一个变量时,你只声明了一个变量,它在每个循环中被覆盖。在循环之后的异步回调中,变量就是最后一次迭代的值。您可以通过使用let或定义自调用函数,将迭代值作为参数传递来规避此问题。

for (let i = 0; i < array.length; i++) { ... }

或者

for (var i = 0; i < array.length; i++) {
   (function(i) {
   ...
   })(i);
}

推荐阅读