嗨,我一直在探索闭包和 javascript 核心概念,我无法理解为什么 console.log(factory[i]) 输出未定义,我已将我的函数插入其中,对吗?如果我在循环外调用 temp,它会显示未定义,而如果我在循环内调用,它会返回有点困惑,有人可以解释一下吗?这是我的代码
var fruits=["apple","orange"];
var factory=[];
for(var i=0;i<fruits.length;i++)
{
var temp=function()
{
console.log(fruits[i]);
}
factory.push(temp());
}
temp();
console.log(factory);
for(var i=0;i<factory.length;i++)
{
temp(i);
console.log(factory[i]);
}
最佳答案
您传递的不是函数,而是执行函数 temp() 的结果,因为它不会返回任何未定义的内容。
更改工厂.push(temp());到工厂.push(temp);
外部的 temp() 返回未定义,因为此时循环已执行并且 i 的值为
2
检查以下记录 i 值的代码。
var fruits=["apple","orange"];
var factory=[];
for(var i=0;i<fruits.length;i++)
{
var temp=function()
{
console.log(fruits[i],"console",i);
}
factory.push(temp);
}
temp();
console.log(factory,"factory");
for(var i=0;i<factory.length;i++)
{
temp(i); //i resets to 0 here in same scope
console.log(factory[i](i),"factoryi"); //this doesnt return anything so its undefined but statements are executed
}
关于javascript - 带函数的 JavaScript 闭包是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43447444/