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?
仅有的幸福2017-05-19 10:32:05
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.
This function will return an array of functions.
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.
function createFunction(){
var result = new Array();
for (var i = 0; i < 10; i++) {
result[i] = function(){
return i;
}();
}
return result;
}
createFunction() //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
漂亮男人2017-05-19 10:32:05
Because you are just assigning functions to array elements and not calling these functions.
function createFunction(){
var result = new Array();
for (var i = 0; i < 10; i++) {
result[i] = (function(){
return i;
})();
}
return result;
}
PHP中文网2017-05-19 10:32:05
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
createFunction().forEach(fn => console.log(fn()));