javascript calling function as array element -
i came across example in toptal youtube video uses syntax won't run in chrome, unless missing something. example comes here (javascript closure inside loops – simple practical example) , same syntax used. why not running me/does indicated line below contain valid syntax?
var x, y, funcs = []; for(x=0; x<5; x++){ (function(){ var r = x; funcs.push(function(){ console.log(r); }); }); }; (var y=0; y<5; y++){ funcs[y](); //<< valid js syntax/why not working me? };
you need make anonymous function inside first for-loop self-executing adding pair of brackets ()
after definition.
(function(){ var r = x; funcs.push(function(){ console.log(r); }); })();
without this, keep declaring function inside first loop never executed , thus, never pushes array.
after first loop, console.log(funcs.length)
, 0
since array has no elements.
your current code give uncaught type error: funcs[0] not function
because funcs[0]
undefined
.
Comments
Post a Comment