var a = [];
for (var i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
}
}
a[6]();//10
等价于
var a = [fn, fn, fn, fn, fn, fn, fn, fn, fn,fn];
var i = 10;
function fn() {
console.log(i);
}
a[6]();//10
要想让a6输出的结果为6,将for循环的var改成let即可,修改代码如下:
var a = [];
for (let i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
}
}
a[6]();//10
关于var 和 let 区别,感兴趣的可以自己百度一下.