javascript - how do you execute a function on the returned value of another function? -
javascript - how do you execute a function on the returned value of another function? -
in next code professional javascript web developers, author says should array of length 10 value of 10 in each position. however, getting array of functions--not values. why that?
function createfunctions(){ var result = new array(); (var = 0; < 10; i++){ result[i] = function(){ homecoming i; }; } homecoming result; // } console.log(createfunctions());
and here console readout:
[function (){return i;}, function (){return i;}, function (){return i;}, function (){return i;}, function (){return i;}, function (){return i;}, function (){return i;}, function (){return i;}, function (){return i;}, function (){return i;}]
edit: tried prepare next code, still getting same console readout:
function createfunctions(){ var result = new array(); (var i=0; < 10; i++){ result[i] = function(num){ homecoming function(){ homecoming num; }; }(i); // } homecoming result; } console.log(createfunctions());
i don't have book, believe found illustration trying in book's code, available download publisher.
the author trying show reference variable i
captured, executing functions returns 10 rather 0 through 9 expected (since i
has value 10
when loop ends).
here code, original document.write
replace console.log
. mentioned in comments, need execute functions in order see output described author.
function createfunctions(){ var result = new array(); (var i=0; < 10; i++){ result[i] = function(){ homecoming i; }; } homecoming result; } var funcs = createfunctions(); //every function outputs 10 (var i=0; < funcs.length; i++){ //document.write(funcs[i]() + "<br />"); console.log(funcs[i]()); }
javascript arrays closures
Comments
Post a Comment