code 问题代码
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
如果我的文章有帮上什么忙并且您也愿意赏个脸 就扫码领个红包吧(~ ̄▽ ̄)~