1. let与const
(1) var声明的变量不受块级作用域的影响,但是let申明的作用域受块级作用域的影响(在块级作用域内起作用)
(2)使用let或者const声明的变量,不能被重新声明。
(3)let不存在"变量提升",也就是预解析时不会提前
(4)暂存死区(了解)
(5)const 常量,申明的时候必须赋值,和let的不同在于一个是常量,一个是变量
(6)常量为引用类型的时候,可以修改该引用类型。指向的地址不能改变,但是对象里的内容是可以改变的。
(7)为了防止常量为引用类型时能被修改的情况,使用Object.freeze()方法将对象冻结。
(8)es6之前申明常量
var BASE_COLOR="#fff";//假装是常量
//Object.defineProperty();
var CST={a:1};
Object.definePropertu(CST,'a',{
writable:false //只读
});
Object.seal(CST);//可以修改对象,但是不能扩展对象
Object.defineProperty()和Object.seal()结合在一起使用,第一个函数保证了只读,但是可以扩展,第二个函数保证了扩展,但是可写。二者结合就保证它既不可扩展,也不可写
2. ES6的解构赋值
(1)数组的解构赋值
const arr=[1,2,3,4];
let[a,b,c,d]=arr;
const arr2=[1,2,[3,4,[5,6,7]]];
let[,b]=arr;//b=2
let[,,g]=arr;//g=[3,4,[5,6,7]]
let[,,[,,[,,h]]]=arr;//h=7
//扩展运算符 ...
const arr1=[1,2,3];
const arr2=['a','b'];
const arr3=['zz',1];
const arr=[arr1,arr2,arr3]; //[[1,2,3],['a','b'],['zz',1]]
const arr2=[...arr1, ...arr2, ...arr3]; //[1,2,3,'a','b','zz',1]
const array=[1,2,3,4];
const [a,b,...c]=arr; //a=1,b=2,c=[3,4]
//交换变量
let a=20;
let b=10;
[a,b]=[b,a];
//接受函数的多个返回值
function gerUserInfo(id){
return [
true,
{
name:'小明',
gender:'女',
id:id
},
'请求成功'
]
}
const[status, data, msg]=getUserInfo(123);//status=true, data={}, id=123
(2)对象的解构赋值
const person={
name:'zhangsan',
skill:[{
name:'111',
age:20
},{
name:'222',
age:20
},{
name:'333',
age:20
}]
};
const{name}=person;
const{skill}=person;
const{skill:[skill1,{name:name1},{name:name2}]}=person;
console.log(name);//zhangsan
console.log(skill);//[{},{},{}]
console.log(skill1);//[{name:'111',age:20}]
console.log(name1);//222
console.log(name2);//333
//综合扩展运算符
const obj={
a:1,
b:2,
c:3
};
const{a,...d}=obj;
console.log(a);//1
console.log(d);//{b:2,c:3}
const pObj={
d:4,
...obj
}
console.log(pObj);
//对已经申明的变量进行对象的解构赋值
let age;
{age}=obj;//出错,会当作块级作用域处理
({age}=obj);//加个小括号解决
(3)字符串的解构赋值
const str='I am the bone of my sword';
const[a,b,c,...oth]=str;//a="I",b="",oth= ["m", " ", "t", "h", "e", " ", "b", "o", "n", "e", " ", "o", "f", " ", "m", "y", " ", "s", "w", "o", "r", "d"]
const[...spStr1]=str;//spStr1=["I", " ", "a", "m", " ", "t", "h", "e", " ", "b", "o", "n", "e", " ", "o", "f", " ", "m", "y", " ", "s", "w", "o", "r", "d"]
const spStr2=str.split('');//spStr2=["I", " ", "a", "m", " ", "t", "h", "e", " ", "b", "o", "n", "e", " ", "o", "f", " ", "m", "y", " ", "s", "w", "o", "r", "d"]
const spStr3=[...str];//spStr3=["I", " ", "a", "m", " ", "t", "h", "e", " ", "b", "o", "n", "e", " ", "o", "f", " ", "m", "y", " ", "s", "w", "o", "r", "d"]
(4)数值与布尔值的解构赋值
(5)函数参数的解构赋值