var js and let the scope and issues

Today learning ES6, I noticed the difference between the var and let.

There are a = [];

for(var i=0;i<10;i++){

   a[i]=funciton(){

       console.log(i);

   };

 }

a[6]();  //10

for(var i=0;i<a.length;i++){

  a [i] (); // outputs 0-9

}


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

var set global variables. Is stored in the array i points to the memory address, so that in the cycle has been changing i, in the last 10 does not move. 

let local variable is set, the variable declaration is only valid within the block-level action. The variable i is only valid in the current round of cycle, so the array is written to the current round of i, i of each round is a new variable. You can see concrete

http://es6.ruanyifeng.com/#docs/let

I am myself a scope to learn well, so I checked the Internet under the understanding js scope.

First, the scope of the internal function is

There are a = 10;

function aaa(){

  console.log(a);
  var a=20;

}

aaa();    //undefined

Here there is a function of the internal and external scope scope, there are two conflicting first selects itself according to the principle of proximity undefined. This is my own understanding, if there is something wrong, please correct me.

There are a = 10;

function  aaa(){

  cosonle.log(a);

  a = 20; // global variable is not var

}

aaa();    //10


There are a = 10;

function aaa(){

 var a = 20; // function within the scope

 cosole.log(a);   //20

}
Released nine original articles · won praise 0 · Views 3317

Guess you like

Origin blog.csdn.net/qq_27568213/article/details/80620010