'in JS I Don't Know this Expression
function makeArmy() {
let shooters = [];
for (let i = 0; i < 10; i++) {
let shooter = function() {
alert(i);
};
shooters.push(shooter);
}
return shooters;
}
let army = makeArmy();
army[0](); < -- - what is this ?
army[5](); < -- - what is this ?
Solution 1:[1]
Let's do this back-to-front:
let army = makeArmy();
That calls a function...
// ...and the function
function makeArmy() {
// Creates an array
let shooters = [];
// It loops from 0 to 9 pushing a new function
// into the array on each iteration
for (let i = 0; i < 10; i++) {
// Create the new function
let shooter = function() {
// I used console.log because it's much less hassle :)
console.log(i);
};
// Add the function to the array
shooters.push(shooter);
}
// And then you return the array of functions
return shooters;
}
// An array of functions!
let army = makeArmy();
// Call the first function in the array
army[0]();
// Call the fourth function in the array
army[3]();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andy |
