Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 views
in Technique[技术] by (71.8m points)

这串代码为什么会这样输出?

for ( var i = 0 ;i<5;i++){

    setTimeout((function(i){
        console.log('1',i);
            var j= i;
        return function(){
            console.log('2',j);
        }
    })(i),i*1000)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

第一个匿名函数立即执行,它不会进行等待,在for的每次循环都会立即执行,所以会输出1,0;1,1;...;1,4;而且匿名函数里面返回了一个函数,这个函数会在对应的延迟后执行(延迟的时间不一定是i*1000ms,这要看你for循环消耗的时间长短);而且立即执行函数返回一个匿名函数,形成闭包,导致输出的是2,0;2,1;...;2,4


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...