JS in the For loop inside define the function to use the self-increment variable generated problem

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.