For-loop saving state with closure

坚强是说给别人听的谎言 提交于 2019-12-05 08:15:27
thefourtheye

Because you are returning the value returned by the IIFE immediately, in this statement

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. To fix this, just drop the return keyword,

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

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!