for(var i=0;i<5;i++){
setTimeout(function(){
console.log('delayer:' + i );
}, 0);
console.log(i);
}
//输出:
0
1
2
3
4
delayer:5
delayer:5
delayer:5
delayer:5
delayer:5
闭包实现:delayer: 0, delayer:1…
//方法一:
for(var i=0;i<5;i++){
(function(){
var n=i;
setTimeout(function(){
console.log('delayer:' + n );
}, 0)
})();
console.log(i);
}
//方法二:
for(var i=0;i<5;i++){
(function(n){
setTimeout(function(){
console.log('delayer:' + n );
}, 0)
})(i);
console.log(i);
}
//以上两种方法输出:
0
1
2
3
4
delayer:0
delayer:1
delayer:2
delayer:3
delayer:4
//方法三:
for(var i=0;i<5;i++){
setTimeout(function(n){
console.log('delayer:' + n );
}(i), 0);
console.log(i);
}
//输出:
delayer:0
0
delayer:1
1
delayer:2
2
delayer:3
3
delayer:4
4