前端面试小题目
for(var i=0; i<4; i++) {
setTimeout(function() {
console.log('setTimeout: ', i);
}, 0);
console.log(i);
}
/*
* output
* 0
* 1
* 2
* 3
* setTimeout: 4
* setTimeout: 4
* setTimeout: 4
* setTimeout: 4
*/
for(var i=0; i<4; i++) {
(function(len){
setTimeout(function(){
console.log('function: ', len);
},0)
})(i);
console.log(i);
}
/*
* output
* 0
* 1
* 2
* 3
* function: 0
* function: 1
* function: 2
* function: 3
*/
var len=4; while(len--){ setTimeout(function(){ alert(len); },0); alert(len); }
// output: 3,2,1,0,-1,-1,-1,-1.
var len=4; while(len--){ (function(i){ setTimeout(function(){ alert(i); },0); })(len); alert(len); }
// output: 3,2,1,0,1,2,3,0