Let 和 Const 命令
Let
let 功能和 var 类似只不过声明的变量只在自己的作用域内有效
{ var i = 10; let j = 0; } //10 console.log(i); //undefined; console.log(j);
不存在变量提升
//undefined,相当于: //var i; //console.log(i); //i = 10; console.log(i); var i = 10; //ReferenceError console.log(j); let j =10;
TDZ(暂时性死区)
我的理解就是在当前作用域内该变量被绑定,不受外部影响,该变量只有被声明过后才能被使用
var temp =10; { //ReferenceError: temp is not defined console.log(temp); let temp = 5; }
不能在同一个作用域内重复声明变量
//error function test(){ let a = 10; var a = 10; }
const
const 用来声明常量,声明之后必须马上赋值,不然会出错,基本用法规则和 let差不多
//err const a;
const 声明引用类型的常量的时候,定义的是它的地址,它的值本身是可以改变的
const a = []; //这种表达是正确的 a.push('dd'); //error a = [2,3]
如果要冻结对象的值,可以使用Object.freeze()方法
const a = [2,3]; Object.freeze(a); //error a.push(1);
跨模块常量
//example.js
export const a = 10;
export const b = 20;
//test1.js
import * as data from './example';
//10
console.log(data.a);
//20
console.log(data.b);
//test2.js
import {a,b} from './example';
//10
console.log(a);
//20
console.log(b);
全局对象属性
let 和 const 声明的变量都不是全局对象的属性
var a = 20; //20; console.log(window.a); let b = 10; //10 console.log(window.b);
解构赋值
数组解构赋值
对多个变量进行赋值,变量值对应相等
//x=1,y=2,z=3 let [x,y,z] = [1,2,3]
没有指定值默认为undefined
//x=1,y undefined let [x,y] = [1];
指定值个数大于变量值,变量值依次结构
//x = 1 let [x] = [1,2,3];
前后的格式都是可以遍历的数据结构且一定要相同,不然就会出错
//error let [x] = 2
也可以在左边直接给变量赋值,这时候要注意和右边的值冲突,我的理解是只有右边对应的值是undefined的时候左边的值才会起作用
//x = 1, y = 2,此时起作用 let [x,y=2] = [1,undefined]; //x = 1, y =null,此时左边的值(默认值)不会起作用 let [x,y=2] = [1,null]; //x = 3, y=4,此时不起作用 let [x=1, y=2] = [3,4];
- 在结构赋值的时候,一个变量只有被声明之后才可以被使用
//error,y 没有被声明
let [x = y ,y=1] =[]
对象的解构赋值
变量名和属性名相同
//x = 1, y =2,相等于 let{x:x, y:y} = {x:1,y:2} let {x,y} = {x:1,y:2};
变量名和属性值不相同,注意真正传递的数据是属性值,而不是变量名
//foo = 1 ,bar = 2 let {x:foo,y:bar} = {x:1, y:2}
注意属性名和变量名的声明是同时的
//error,bar 被重复声明 let bar; let {foo:bar} = {foo:1}; //正确,bar没有重复声明,作用域不通 let bar; (let {foo:bar} = {bar:1})
结构赋值嵌套
//line =1 ; //loc undefined //start undefined //在这个了例子中,只有line是变量,其他值都是模式 var node = { loc:{ start:{ line:1 column:5 } } }; var {loc:{start:{line}}} = node;
字符串的解构赋值
字符串也可以结构赋值
//a= 'h' //b = 'd' //.... var [a,b,c,d,e] = 'hello'; //len = 5; let {length : len} = 'hello';
用途
遍历Map
//first is hello //second id world var map = new Map(); map.set('first','hello'); map.set('second','world'); for(let [key,value] of map){ console.log(key+'is'+'value'); }