带闭环的环路保存状态 [英] For-loop saving state with closure
问题描述
原谅我,如果这可能是一个noobie问题,但这应该工作不应该吗?
Forgive me if this might be a bit of a noobie question, but this should work shouldn't it?
var elems = [1,2,3,4,5]
for (var i = 0; i <elems.length; i++) {
return (function(e){
console.log(e)
})(i);
}
意味着应该吐出
>>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
我缺少什么?
推荐答案
因为您在此语句中立即返回由IIFE返回的值
Because you are returning the value returned by the IIFE immediately, in this statement
return (function(e){
console.log(e)
})(i);
因为IIFE只是输出 0
不显式返回任何值,JavaScript将默认返回 undefined
,立即退出。要解决这个问题,只需删除 return
关键字
since the IIFE just prints 0
and doesn't return anything explicitly, JavaScript will return undefined
by default and exit immediately. To fix this, just drop the return
keyword,
(function(e){
console.log(e)
})(i);
PS:你曾经想过,为什么上述代码中的 return
语句有效?想想它,它不是在一个函数内。然后在技术上它的一个错误,对吧? ;-)我在这个问题中详细解释了这一点。
PS: Have you ever wondered, why the return
statement in the above code works? To think about it, it is not inside a function. Then technically its an error, right? ;-) I explained this in detail, in this question.
这篇关于带闭环的环路保存状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!