Home > front end >  This example let me to var and let very dizzy... Which potential solutions?
This example let me to var and let very dizzy... Which potential solutions?

Time:01-12

 function count () {
Var arr=[];
For (var I=1; i<=3; I++) {//var
Arr. Push (function () {
Return the I * I;
});
}
return arr;
}

The var results=the count ();
Var f1=results [0];
Var f2=results [1].
Var f3=results [2];

Alert (f1 ());//16
Alert (f2 ());//16
Alert (f3 ());//16


Why, after changing the let output changed?

 function count () {
Var arr=[];
For (the let I=1; i<=3; I++) {//let
Arr. Push (function () {
Return the I * I;
});
}
return arr;
}

The var results=the count ();
Var f1=results [0];
Var f2=results [1].
Var f3=results [2];

Alert (f1 ());//1
Alert (f2 ());//4
Alert (f3 ());//9


Don't have to go into the var and let scope is different, I know that the var of the count function effectively, let applies only to the for loop,

I saw this problem for var return I are 4 explanation is "the returned function reference variable I, but it is not immediately, wait until three functions are all returned, they are the referenced variable I had become a 4", my question is, with the let, how "immediately" and return to I=1, 2, 3?

CodePudding user response:

Is a scoped variables declared with the let, when using the let in a for each loop will be in the loop body block scope to create a new variable, I
Each loop body piece of scope and block scope are interlinked to create the function of the function, form a "closure",
Closure can let every piece of the I variable scope and its reserves, will not be system recovery,
From creation function when this function is called when the block scope take the I variable is retained,

CodePudding user response:

reference 1/f, the sky wave response:
is a scoped variable declared with the let, when using the let in a for each loop in the loop body block scope to create a new variable, I
Each loop body piece of scope and block scope are interlinked to create the function of the function, form a "closure",
Closure can let every piece of the I variable scope and its reserves, will not be system recovery,
When this function is called when from creation function block scope take the I variable is retained,

Thank you,
Can explain why var under this case, "is not immediately run until I become a 4" began to perform I * I?

CodePudding user response:

The var statement I always only one,
You created three functions in a loop, but the function is after the cycle, cycle has ended, I value is the maximum cycle plus 1,
  • Related