站内搜索:
首页 >> 前端 >> 内容
关于For循环中进行异步操作索引不正确的解决方案

时间:2017/11/28 3:10:28

关于For循环中进行异步操作索引不正确的解决方案

function test() {
    for (var i = 0; i < 5; ++i) {
        setTimeout(function() {
            console.log("index is :", i);
        }, 1000);
    }
}
test();

output 问题输出

index is : 5
index is : 5
index is : 5
index is : 5
index is : 5

solution 使用自执行函数

function test() {
    for (var i = 0; i < 5; ++i) {
        (function(i){
            setTimeout(function() {
                console.log("index is :", i);
            }, 1000)
        })(i);
    }
}
test();

output 正确输出

index is : 0
index is : 1
index is : 2
index is : 3
index is : 4

  • 上一篇:创建本地工程文件和网络映射方式讲解
  • 下一篇:HTML中CSS如何去除li前面的小黑点?
  • 返回顶部