javascript - Closures inside loops and local variables -


this question has answer here:

i js novice , reading closures, common issues arise due misunderstanding how closures work , "setting handlers inside loop" pretty example. i've seen , understood ways around this, i.e, calling function passing loop variables arguments , returning function. tried take dip see if there other ways around , created following code.

var i;  var inparr = new array();  for(i = 0; < 10; ++i) {   inparr.push(document.createelement("input"));   inparr[i].setattribute("value", i);   inparr[i].onclick = function() {     var index = i;     alert("you clicked " + index);   }   document.body.appendchild(inparr[i]); } 

it doesn't work guessed don't understand why. understand i captured , made available function expressions generated. why still not work after assigning captured variable local variable index? isn't assigning i same passing i argument function? mean, isn't i primitive , isn't supposed copied?

i confused , appreciate if tell me what's going on here.

i think expecting var index = i; being executed in every iteration of loop, there setting different values different index variables, not happens. during each iteration function assigned handler, function not run.

this sentence gets executed when click, time value of i highest value per loop. exact problem solved solutions read.

what happens during loop:

inparr[0].onclick = <a function>; //(local)index=undefined; i=0; inparr[1].onclick = <a function>; //(local)index=undefined; i=1; inparr[2].onclick = <a function>; //(local)index=undefined; i=2; inparr[3].onclick = <a function>; //(local)index=undefined; i=3; . . inparr[9].onclick = <a function>; //(local)index=undefined; i=9; 

and when click

index = i; //i=9; (local)index=9; 

Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -