简体   繁体   English

具有闭包的For循环保存状态

[英]For-loop saving state with closure

Forgive me if this might be a bit of a noobie question, but this should work shouldn't it? 原谅我,如果这可能是一个noobie问题,但这应该工作不应该吗?

var elems = [1,2,3,4,5]

for (var i = 0; i <elems.length; i++) {
    return (function(e){
        console.log(e)
    })(i);
}

Meaning, it should spit out 意思是,它应该吐出来

>>node file.js
1
2
3
4
5

For some reason this isn't doing this. 出于某种原因,这不是这样做的。 Rather when it is run in terminal, it spits out 而是当它在终端中运行时,它会吐出来

>>node file.js
1

What am I missing? 我错过了什么? Could you please elaborate. 你能详细说明吗?

Because you are returning the value returned by the IIFE immediately, in this statement 因为您在此声明中立即返回IIFE返回的值

return (function(e){
    console.log(e)
})(i);

since the IIFE just prints 0 and doesn't return anything explicitly, JavaScript will return undefined by default and exit immediately. 由于IIFE只打印0并且没有明确返回任何内容,因此JavaScript将默认返回undefined并立即退出。 To fix this, just drop the return keyword, 要解决此问题,只需删除return关键字,

(function(e){
    console.log(e)
})(i);

PS: Have you ever wondered, why the return statement in the above code works? PS:你有没有想过,为什么上面代码中的return语句有效? To think about it, it is not inside a function. 想一想,它不在函数内部。 Then technically its an error, right? 然后技术上是一个错误,对吗? ;-) I explained this in detail, in this question . ;-)我在这个问题中详细解释了这一点。

When you call the return, it will immediately break out of the loop. 当您调用返回时,它将立即突破循环。 If you want to return all the values, you will have to put them in a container and return the container. 如果要返回所有值,则必须将它们放在容器中并返回容器。

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

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