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, IEach 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: