带函数的Javascript闭包是如何工作的?
您好,我一直在探索闭包和javascript核心概念,我不明白为什么console.log(factory[i])输出未定义,我把函数推到了里面,对吗?如果我在循环外调用temp,它表示未定义,而如果我在循环内调用,它返回的结果有点混乱,有人能解释我吗?这是我的代码带函数的Javascript闭包是如何工作的?,javascript,function,closures,lexical-closures,Javascript,Function,Closures,Lexical Closures,您好,我一直在探索闭包和javascript核心概念,我不明白为什么console.log(factory[i])输出未定义,我把函数推到了里面,对吗?如果我在循环外调用temp,它表示未定义,而如果我在循环内调用,它返回的结果有点混乱,有人能解释我吗?这是我的代码 var fruits=["apple","orange"]; var factory=[]; for(var i=0;i<fruits.length;i++) { var temp=function() {
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]);
}
var fruits=[“苹果”、“橘子”];
var工厂=[];
对于(var i=0;i,这里是您的输出
//next two executed due to factory.push(temp()) in first if loop
& there is a console.log there inside the function
apple
orange
//here i++ in first loop will be 3, but array have only two element, so it is undefined
undefined
// due to console.log(factory)
// temp function is actually returning undefined,
[undefined, undefined]
// due to temp(i) in second if block
apple
// but factory array is stil empty so factory[i] will be undefined
undefined
from temp orange
undefined
您传递的不是函数而是已执行函数temp()的结果,因为它不会返回任何未定义的内容。更改factory.push(temp());改为factory.push(temp);
外部的temp()返回未定义,因为此时循环已执行,且i的值为2
请检查以下记录i值的代码段
var fruits=[“苹果”、“橘子”];
var工厂=[];
对于(var i=0;i闭包只不过是保留数据的函数。到目前为止,函数被视为代码的和平,它接受输入并产生一些输出,对于每个函数调用,此代码保持不变,但闭包让您有机会使用可以更改的函数保存一些数据,以便对每个函数调用作出不同的反应记住,一切都会很容易的
假设您有一个查找利率的函数,但该函数由三个利率不同的团队使用,因此通常我们传递团队名称和原则金额,每次我们都必须传递团队名称,因此通过使用闭包,我们可以为每个团队传递三个函数实例(团队名称作为保留数据)现在只发送原则金额,并根据团队计算利息,我稍后还会添加示例,显示的所有代码共享相同的I
变量。此外,您从不调用工厂
数组中的任何函数,您只调用最后一个temp()
函数已创建。您好,我理解,谢谢,所以我知道有什么问题吗