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); // 5 let {toString} = 123; toString === Number.prototype.toString // true3、注意事项
块级作用域
什么是块级作用域?
一个 {} 就是一个块级作用域
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命令,它所公告的变量就“绑定”(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