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