ES6标准入门中let命令提到的for循环打印i是10,如果不用let怎么替换?

最近在读阮一峰老师的ES标准入门,读到第一章的时候提到了一段代码

var a = [];

for (var i = 0; i < 10; i++) {

  a[i] = function () {

    console.log(i);

  };

}

a[6](); // 10

如果想要输出6,用let就可以解决这个问题,但是如果用ES5的方法呢?IIFE可以做到,不过是立即打印出来。

缥缈止盈
浏览 444回答 1
1回答

温温酱

var a = [];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(var i = 0; i < 10; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; +function(i){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a[i] = function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }(i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; };a[6](); // 6闭包问题
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript