猿问

学习ES6时let用于for循环时,函数里console的问题

 var a = [];    for (let i = 0; i < 10; i++) {
      a[i] = function () {        console.log(i);
      };
    }
    a[6](); //6
    console.log(a[6]); //  function(){console.log(i)}

既然循环结束后,数组a的每一项都是function(){console.log(i)},那么a[6]()输出是6是怎么实现的?难道let保存了10个状态?



GCT1015
浏览 612回答 1
1回答

慕森王

>&nbsp;console.log(i);&nbsp;&nbsp;//10ReferenceError:&nbsp;i&nbsp;is&nbsp;not&nbsp;definedlet是块作用域声明,出了for循环就失效了~a[6]();&nbsp;//6for&nbsp;(let&nbsp;i&nbsp;=&nbsp;0;&nbsp;i&nbsp;<&nbsp;10;&nbsp;i++)&nbsp;{ &nbsp;&nbsp;a[i]&nbsp;=&nbsp;function&nbsp;()&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;console.log(i); &nbsp;&nbsp;}; }在匿名函数作用域中log(i)引用了上层作用域的变量&nbsp;i,构成闭包。a[i]中保存了10个闭包,各自保留了构成闭包时变量&nbsp;i的值。2个闭包栗子~> var f=function(){...&nbsp; let i=0;...&nbsp; return function(){.....&nbsp; i=i+1.....&nbsp; return i.....&nbsp; }}()undefined> f()1> f()2> f()3> f()4> f()5> var fn;undefined> for(let i=-1;i<0;i++){...&nbsp; &nbsp; &nbsp;fn=function(){.....&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;i=i+1.....&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return i.....&nbsp; &nbsp; &nbsp;}... }[Function]> fn()0> fn()1> fn()2> fn()3>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答