for (var index = 0; index < 5; index++) {
setTimeout(function (){
console.log(index);//5
}, 10)
}
console.log(index)// 5
这是个陈词滥调的题目,然则本日我才邃晓过来现实是怎么回事。
运用ES6语法的话,修正以下
for (let index = 0; index < 5; index++) {
setTimeout(function (){
console.log(index);//0,1,2,3,4
}, 10)
}
console.log(index)// ReferenceError: index is not defined
var是在全局局限有用,所以实行setTimeout里的函数时,先是在函数内部寻觅 index 变量,没有找到,所以去外层找,找到!这时候index已实行完轮回,所以值为5;
而let则是声明在for轮回的内部的,每一次for轮回,一个block上下文,每次for轮回都竖立以下block。
{
let index = 0;
setTimeout(function (){
console.log(index);
}, 10)
}
这也就诠释了以下代码运转一般
for(const index of array)
那末,var的for轮回里发生了什么呢?
var index;//变量提拔
{
index = 0;
setTimeout(function (){
console.log(index);
}, 10)
}