let|let 命令总结

1、基础语法

let a = value const b = value

语法类似 var
2、进阶语法
  • ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)。
  • 这种写法属于“模式匹配”,只要等号两边的模式相同,左边的变量就会被赋予对应的值。下面是一些使用嵌套数组进行解构的例子。
  • 如果等号右边是数值和布尔值,则会先转为对象。
let [a, b, c] = ['a', 'b', 'c']console.log(a); //'a' console.log(b); //'b' console.log(c); //'c'let {a1, b1, c1} = {a1: 'a', b1: 'b', c1: 'c'}; console.log(a1); //'a' console.log(b1); //'b' console.log(c1); //'c'let [a2, b2, c2, d2, e2, f2] = "string"console.log(a2); //'s' console.log(b2); //'t' console.log(c2); //'r' console.log(d2); //'i' console.log(e2); //'n' console.log(f2); //'g'let {length} = 'hello'; console.log(length); // 5let {toString} = 123; toString === Number.prototype.toString // true

3、注意事项 块级作用域
什么是块级作用域? 一个 {} 就是一个块级作用域 for循环的计数器,就很合适使用let命令。
for (let i = 0; i < 10; i++) { // i 只在for的循环体里有效 }console.log(i); //Uncaught ReferenceError: i is not defined

无变量提升
它所声明的变量一定要在声明后使用,否则报错。
console.log(a); //Uncaught ReferenceError: a is not definedlet a = 1;

有暂时性死区
【let|let 命令总结】只要块级作用域内存在let命令,它所声明的变量就“绑定”(binding)这个区域,不再受外部的影响。
let a = true; if (a) { console.log(a); //Uncaught ReferenceError: a is not defined let a = 1; }

不许重复声明
let a = 0; let a = 2; // Uncaught SyntaxError: Identifier 'a' has already been declared

let a = 0; var a = 1; // Uncaught SyntaxError: Identifier 'a' has already been declared

    推荐阅读