关于For循环中进行异步操作索引不正确的处理方式

来源:互联网 发布:淘宝店铺男装推荐 编辑:程序博客网 时间:2024/06/05 03:25

code 问题代码

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

output 问题输出

index is : 5index is : 5index is : 5index is : 5index 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 : 0index is : 1index is : 2index is : 3index is : 4
阅读全文
0 0