A very simple variable leakage problem in js

var a = [];
for (var i = 0; i < 10; iPP) {
  a[i] = function () {
    console.log(i);
  };
}
a[6](); // 10

variable leakage causes the above a [6] to become 10;
I don"t quite understand why a [6] is 10 here. My wrong thinking is as follows

  1. a [6] there are no variables here, so the memory leak comes from the loop
  2. In the
  3. loop, each time the current degree is assigned to the corresponding array,

a [0] = function () {console.log (0);};
a [1] = function () {console.log (1);};
.
a [9] = function () {console.log (9);};
the value of I is correct each time. After the assignment, each function outputs a fixed number, and there is no variable
3. May I ask what is wrong with my thinking

Mar.04,2021

this question has been asked badly and answered many times.
I is the global variable function call to get I now I has been looped to 10
the following is a simple example that can be understood as going through two loops

var i = 1;
function a1(){ console.log(i) }

var i = 2;
function a2(){ console.log(i) }

a1();//2
a2();//2

solution to change I into a local variable

es6
{
  let i = 1;
  function a1(){ console.log(i) }
}

{
  let i = 2;
  function a2(){ console.log(i) }
}

a1();//1
a2();//2
//es6 let
for(let i=0;i<10;iPP) ...
//or
// es5 
for (var i = 0; i < 10; iPP) {
  a[i] = (function(i){
      return function () {
            console.log(i);
          };
  })(i)
}

the problem stems from the lack of a deep understanding of the function scope (chain). Here is a personal opinion, which I hope can help you:

    var a = [];
    for (var i = 0; i < 10; iPP) {   // iwindow
      // i
      a[i] = function () {     
        // ii
        // a[6]fori10 10
        console.log(i);   
      };
    }
    a[6](); // 10
When

executes a [6] (), I has already cycled to 10


closure problem. Students, your foundation should be refueled.


in fact, es6's let doesn't grasp the essence of the problem at all

the key point is that js, as a language that allows side effects, its closure only supports referencing variables in the outer scope, but not "referencing" the value of variables in the outer scope

.

CPP does not have this problem ~

  

simple closure questions, which I have been asked several times during the interview.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b31dda-2bdcf.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b31dda-2bdcf.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?