JavaScript closure issues in a detailed

Source: Internet
Author: User

Before you see a piece of code, it is not understandable, and then find the information and find the network Daniel consulted, finally understand the code, and then take out a summary.

1. Digging pits

Take a look at the code first:

varArrtest = []; for(vari =0; I <3; i++) {//Note that the function does not pass arguments into the function body Arrtest.push (function() {Console. log (' >>> '+ i); })}//arrtest=[function(){Console. log (' >>> '+i)},function(){Console. log (' >>> '+i)},function(){Console. log (' >>> '+i)}]Console. log (arrtest[0].tostring ());//function(){Console. log (' >>> ', +i)}Console. log (i);Console. log ('-------------');//Length can be replaced with l simple words, reduce code length for(vari =0, arrlength = Arrtest.length; i < arrlength; i++) {Console. log (i); Arrtest[i] ();}//The value of the validated IConsole. log (the value of ' I ' is '+ i);//i=3Console. log (' End for '); for(varj =0, arrlength = Arrtest.length; J < Arrlength; J + +) {Console. log (j); ARRTEST[J] ();} Arrtest = [function() {Console. log (' >>> '+ i)},function() {Console. log (' >>> '+ i)},function() {Console. log (' >>> '+ i)}]

The result is like this:

How does that happen when you traverse the entire function and print out the results we want to 0,1,2?

/*对函数进行改造,当执行循环的时候,打印0,1,2 */var arrTest1 = [];for (var03; i++) {    //构造一个立即执行的函数将函数的返回结果添加入数组中    (function(n) {        arrTest1.push(function() {            console.log(‘>>>‘ + n);        });    })(i);}console.log(arrTest1);for (var0, l = arrTest1.length; i < l; i++) {    arrTest1[i]();}

Printing results:

JavaScript closure issues in a detailed

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.