When I was learning the closure problem of js, I typed and experimented with the code examples on js advanced programming, and the results were inconsistent and I couldn’t understand them.
function createFunction(){
var result = new Array();
for (var i = 0; i < 10; i++) {
result[i] = function(){
// console.log(i);
return i;
};
}
return result;
}
The result of this code should be an array, each value is 10, but after experimenting in the browser, I found that what is returned is an array of functions.
So why is it not returning a numerical array?
is an array of functions. Although each function has a return value i, this function is not executed.
Read page 181 of the book carefully, the first sentence below the code.
I was a little confused when I saw this before. I felt that it would be more intuitive to return all 10 directly. After thinking about it, if I add () directly after the returned function, it is equivalent to creating an immediate execution function every time. The returned i is the normal index value every time, which will not achieve the desired effect.
Because you are just assigning functions to array elements and not calling these functions.
result is an array whose elements are functions.
That’s why you are in this situation
If you want to get all you want
10
, just iterate over the array and call the function that is the array element, and log the return value