A phenomenon that you may find very strange.
var batch = [];
var i = 0;
for (; i < 5; i++) {
Batch.push (function Closurefn () {
Console.log (i);
});
}
Batch.foreach (function (item) {item (); Console.log ("<" +i+ ">")});
Output
5
<5>
5
<5>
5
<5>
5
<5>
5
<5>
The output value is the final result of I
What this function does is to store elements in the push array, which is a function and the function is not executed.
So output batch to get
[function Closurefn () {
Console.log (i);
}, Function Closurefn () {
Console.log (i);
}, Function Closurefn () {
Console.log (i);
}, Function Closurefn () {
Console.log (i);
}, Function Closurefn () {
Console.log (i);
}]
Iterate over each item of batch
The item in foreach is
function Closurefn () {
Console.log (i);
} This function
So the item () runs the output of the final I value.
PS batch This array of foreach callback function in the variable i is the global variable i
Or with this example,
var batch = [];
var i = 0;
for (; i < 5; i++) {
Batch.push (function Closurefn () {
return i;
});
}
Batch.foreach (function (f) {Console.log (f ())});
Get 5 of 5
That's the same thing.
Use the immediate execution function to solve this problem
var batch = [];
var i = 0;
for (; i < 5; i++) {
Batch.push (function Closurefn (i) {
Console.log (i+ ". ");
return i;
} (i));
}
Console.log (Batch); [0, 1, 2, 3, 4]
Or so deepen the impression
var batch = [];
var i = 0;
for (; i < 5; i++) {
Batch.push (function closurefn (index) {
return function () {Console.log (i+ "" +index)};
} (i));
}
Batch.foreach (function (item) {Item ()});
Output results
5 0
5 1
5 2
5 3
5 4
The immediate execution function is used here, so every time the Loop parameter index gets the index of the round cycle
PS index is not a reference to I but each time I loop I pass my value to index
Closurefn This function executes immediately and returns a function The returned function is an element in batch
PS closures hold references to external variables instead of values
so after the for loop executes the value of I is already 5 foreach each item i is 5 when executing the return function