I have recently done a lot of candidates for the pen test, one of which makes me very impressive, about in a for loop inside some functions used in the definition of variables inside the for loop problem, Nonsense said, first on the code, you can see the final result of this code is what:
var array=[];//defines an array, empty for (Var i=0;i<3;i++) {array[i]=function () {alert (i); }}array[0] (); array[1] (); array[2] ();
Beginners may look, think, this is not very simple? Eject 0,1,2 in turn. Dear classmates, you can try it yourself, the result will be unexpected, the result is three times 3, the end is why? Let's take a closer look.
This code, when executed, will first create a new global array, an empty array. In each for loop, the contents of the inside of the inside of the for loop are not executed (into) array[i], but in this case the array[i] is added to the global scope chain. After the For loop (I should be equal to 3), that is, at the end of the function initialization, we are now really calling the function we just created, at this time, the program will go back to execute the function inside the body, to output the value of I, but at this point I is 3, so the output is all 3.
Found this problem, we now want to find a way to solve it, unfortunately, the author's JS Foundation thin, also wood has found solutions to solve the problem of array function. However, if it is an object (such as a series of document objects obtained through the LI tag), then I can solve him, as follows:
var array=document.getelementsbytagname ("Li");//Get node element, of course there is not only one contact for (Var i=0;i<3;i++) {array.index=i; Array[i].onclick=function () {alert (this.index); }}//Click to trigger function execution.
This article from "D Tune small Snail" blog, reproduced please contact the author!
JS in the For loop inside define the function to use the self-increment variable generated problem