Recently I was reading Teacher Ruan Yifeng’s Introduction to ES Standards, and when I read the first chapter, I mentioned a piece of code
var a = [];
for (var i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a[6](); // 10
Using let here can solve this problem, but what if we use the ES5 method? IIFE can do it, but it prints it immediately.
Closure problem
You can use custom attributes
var a = [];
for (var i = 0; i < 10; i++) {
}
a[6](); // 6
This has nothing to do with
let
anything, I think the questioner wants to output 6, right?But the question you asked seems completely inconsistent with what you want. I want to help you change the description of the question but I am a little helpless...
This is actually a closure problem. Mainly, let’s first analyze why 10 is output:
The role ofi
in
for
is the entire external area, so whena[6]()
is called,console.log(i)
is actually run, and at this time because it has finished running Loop, the value ofi
is 10, so 10 is output.As for what the questioner said,
let
can be solved because, infor
, the variables declared bylet
only act insidefor
, so it will not causei
due to the completion of the loop. In the global scope it is 10.In fact, what this question really examines should be closure.
The function of closure is similar to the previous function of
let
, which is to isolate local variables from each other without contaminating external variable values. Each closure is an independent area, and the closure passes parameters. It is only used internally by the closure, so the result of outputting 6 can also be achieved.You can use closures
http://www.softwhy.com/articl...
The second half of this article has already explained your questions