Now I am going through self-study on one of the online resources on JavaScript. In addition to theory, it also has puzzles. So, in one of the tasks in the topic "Visibility. Closures" I faced a complete misunderstanding of the solution of the problem that the author proposes (I had only one solution, and I will not consider it - below is the problem with the code and examples from the author) .
The task:
The following code creates an array of shooter-function shooters. According to the plan, each shooter must display his number:
function makeArmy() { var shooters = []; for (var i = 0; i < 10; i++) { var shooter = function() { // функция-стрелок alert( i ); // выводит свой номер }; shooters.push(shooter); } return shooters; } var army = makeArmy(); army[0](); // стрелок выводит 10, а должен 0 army[5](); // стрелок выводит 10... // .. все стрелки выводят 10 вместо 0,1,2...9 Why do all shooters display the same thing? Correct the code so that the arrows work as intended. Offer several fixes. (Question of the author of the task)
Suggested solutions by the author that are not clear to me:
(1) Use the additional function to “catch” the current value of i:
function makeArmy() { var shooters = []; for (var i = 0; i < 10; i++) { var shooter = (function(x) { return function() { alert( x ); }; })(i); shooters.push(shooter); } return shooters; } var army = makeArmy(); army[0](); // 0 army[1](); // 1 I did not understand this solution to the task. What do these second brackets with i give in this variant and why in JavaScript, unlike other normal languages like Java x = i, although the names of the parameters are different. In other words, I do not understand how the i is caught.
(2) Wrap the entire cycle in a temporary function:
function makeArmy() { var shooters = []; for (var i = 0; i < 10; i++)(function(i) { var shooter = function() { alert( i ); }; shooters.push(shooter); })(i); return shooters; } var army = makeArmy(); army[0](); // 0 army[1](); // 1 This solution to the task introduces me even more into a stupor. Where is the i value of each arrow generally stored? What role do the second brackets with the parameter (i) play in all this?