简体   繁体   English

JavaScript闭包和for循环

[英]JavaScript closures and a for loop

I was wondering why the result of the following code is 0 and not 3. 我想知道为什么以下代码的结果是0而不是3。

var fn = function(){
    for (i = 0; i < 3; i++){
        return function(){
            console.log(i);
        };
    }
}();

fn();

Because your return statement forces the loop to terminate and the function to stop executing. 因为您的return语句会强制循环终止,并且函数将停止执行。

You can learn more about return statements here - https://en.wikipedia.org/wiki/Return_statement 您可以在此处了解有关return语句的更多信息return : //en.wikipedia.org/wiki/Return_statement

You're returning a closure that's calling console.log . 您将返回一个调用console.log的闭包。 When you're doing this return statement you're stopping fn() from proceeding, it returns the first thing that needs returning and halts execution. 执行此return语句时,您将停止继续执行fn() ,它返回需要返回的第一件事并停止执行。 Remove the return statement (and closure) if you want to console.log. 如果要console.log,请除去return语句(并关闭)。

var fn = function(){
    for (i = 0; i < 3; i++){
        console.log(i);
    }
}();

fn();

Also See: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/return 另请参阅: https : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/return

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM