The let
statement in ES2015 allows us to declare block scope variables, so that for example the following code does what we want:
let fs = [];
for (let i = 0; i < 3; i++) {
fs.push(() => i);
}
console.log(fs.map(f => f())); // 0, 1, 2
However, it does not seem to work in Firefox with the for…of
loop which iterates over iterable objects. Here, the block scope is ignored, and we get the same result as if we used var
instead:
fs = [];
let nums = [0, 1, 2];
for (let i of nums) {
fs.push(() => i);
}
console.log(fs.map(f => f())); // 2, 2, 2
Why is the behavior of let
not working here, and what’s internally so different about the for…of
loop that this breaks?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…