var vs. let
A block statement is used to group zero or more statements. The block is delimited by a pair of curly brackets.
let (顺序声明,顺序赋值)
Declares a block scope local variable, optionally initializing it to a value.
var (优先声明,顺序赋值)
Declares a variable, optionally initializing it to a value.
为了美观 (var 不受 block scope 制约,所以只是美观),同域,重新声明并赋值
{ // do something 1 var a = 1; console.dir(a); } { // do something 2 var a = 2; console.dir(a); }
真正发挥作用(let 是 block scope 级的),不同域,互不影响
{ // do something 1 let a = 1; console.dir(a); } { // do something 2 let a = 2; console.dir(a); }
let 只能顺序声明,顺序赋值,下面这段程序是错的:
{ // do something 1 console.dir(a); let a = 1; }
var 优先声明,顺序赋值,下面这段程序不会报错,但结果是undefined:
{ // do something 1 console.dir(a); var a = 1; }
let 在本域一旦let 声明某个变量a ,则不可在本域再次声明a(var a; let a;均不可以)
{ var a = 0; let a = 1; let a = 2; var a = 3; }
编译错误,完全不能运行,影响所在的整个<script></script>