varF和letF之间的唯一区别是,在for循环中,用let声明替换为var声明。
那么,为什么输出不同?
let varList = [];
let letList = [];
function letF() {
for (let i = 0; i < 10; i++) {
function log() {
console.log(i);
}
letList.push(log);
}
}
function varF() {
for (var i = 0; i < 10; i++) {
function log() {
console.log(i);
}
varList.push(log);
}
}
varF();
letF();
for (let j = 0; j < 10; j++) {
varList[j](); // expected output: 10,10,10,10,10, ....
}
console.log('-----------------------------');
for (let j = 0; j < 10; j++) {
letList[j](); // expected output: 0,1,2,3,...
}