/**
解构:ES6允许按照一定模式从数组和对象中提取值,然后对变量进行赋值,这被称为解构
本质上,这种写法属于“模式匹配”,只要等号两边的模式相同,左边的变量就会被赋予对应的值。
*/
let [a] = [];
let [b,c] = [1]
console.log(a);//undefined
console.log(b,c,‘dddddd’);//1,undefined
//解构不成功值会为undefined
//有一种情况叫不完全结构:即等号左边的模式只匹配一部分的等号右边的数组
let [x,y] = [1,2,3];
console.log(x,y);//1,2
//解构可以赋默认值
let [z = 1] = [null];//es6里用的是 === 只有严格等于undefined才能默认值生效,否则是不生效的哟!
console.log(z,‘ccccc’);//null
//上面是数组的解构,下面说一下对象的解构
对象的解构和数组不一样的地方在于,他是先找相同的属性名,再给变量赋值,这是本质了
let {foo:aa,bar:bb} = {foo:‘aa’,bar:‘bb’}
console.log(aa,bb,‘ababababa’);
let obj = {
p:[
‘www’,
{eee:‘eee’}
]
}
let {p:[www,{eee}]} = obj;
console.log(www,eee,‘wwweeewwweee’);
//对象解构也可以指定默认值
let {ss,dd = 1} = {ss:2};//同样的,这里用的也是 === 严格等于undefined,默认值才会生效
console.log(ss,dd,‘ssddssdd’);
//要对已经声明的变量进行解构,需要非常小心啦
let cc;
({cc} = {cc:‘dd’})//这里使用了小括号,如果直接将大括号放在前面,引擎会将 {x} 当作一个代码块,这样会报错的!!!!
console.log(cc,‘ccccc’);
//因为数组也是一种特殊的对象,所以可以进行对象解构
let arr = [1,2,3];
let {0:ff,[arr.length - 1]:gg} = arr;//将 0,1 作为属性名称去获取值
console.log(ff,gg,‘ffggffgg’);
//这样的对象解构可以轻松的将对象的方法赋值到某个变量
let {log,sin,cos,PI} = Math;
console.log(log);
console.log(sin);
console.log(cos(PI/3));
console.log(PI);
//字符串的解构赋值
//因为字符串可以转换成一个类似数组的对象
let str = “hello”;
let [q,w,e] = str;
console.log(q,w,e,‘qweqweqwe’);//h,e,l
//也可以使用对象解构
let {length:leg} = str;
console.log(leg,‘leglegleg’);//5 因为str有 length 属性,所以也可以这样使用滴!!!
//数值和布尔值的解构
//对于等号右边不是对象的会先转成对象再进行解构
let {toString:ww} = 123;
console.log(ww == Number.prototype.toString,‘ww ww ww’);//true ww 的值为一个函数
//布尔值同上
//函数参数解构赋值
[[1,2],[3,4]].map(([x,y]) => {
console.log(x + y);
});
function more({x = 0,y = 0} = {}){
//这里是为变量进行赋默认值 {x = 0,y = 0} = {} 进行解构 得到 x = 0,y = 0
console.log(x,y,‘xyxyxyxy’);
}
more({x:3,y:8});//3,8
more({x:3});//3,0 同理:{x = 0,y = 0} = {x:3}
more({});//0,0
more();//0,0
//还有一种写法
function mores({x,y} = {x:0,y:0}){
//这里解构的时候是为参数赋值 {x,y} = {x:3,y:8}
console.log(x,y,‘xxyyxxyyxxyy’);
}
mores({x:3,y:8});//3,8
mores({x:3});//3,undefined 同理 {x,y} = {x:3} 所以 y 为 undefined
mores({});//undefined,undefined {x,y} = {}
mores();//0,0 {x,y} = {x:0,y:0}
//这个解构的用途很广泛
//交换变量的值
let d = 3;
let f = 4;
[d,f] = [f,d];
console.log(d,f,‘dfdfdfdf’);//4,3
//从函数返回很多值,取出的时候就会很方便
function df(){
return [1,2,3];
}
let [s,d,f] = df();
console.log(s,d,f,‘dfdfdfdfdf’);//1,2,3
//函数参数的定义,可以方便的和变量名字联系起来
function f([a,b,c]){
console.log(a,b,c,‘aaaaa’);
}
f([1,2,3]);//1,2,3
function d({w,e,r}){
console.log(w,e,r,‘wwwww’);
}
d({e:3,r:4,w:5});//5,3,4
//提取JSON数据
let obj = {
id:23,
age:12,
name:‘王狗蛋’,
sex:‘男’
}
let {name,sex,age,id} = obj;
console.log(name,sex,age,id,‘fffffff’);
//函数参数的默认值,这样就省下了需要判断参数是否传了
function fun({
name=’’,
age=0,
sex=’’,
id=0
}){
console.log(name,age,sex,id,‘sssss’);
}
fun({name:‘王铁柱’,sex:‘女’});//王铁柱,女,0,0
//遍历Map结构
let map = new Map();
map.set(‘a’,23);
map.set(‘b’,‘bb’);
for(let [key,value] of map){
console.log(key,value,‘vvvvvv’); //a,23 b,bb
}
//输入模块的指定方法 let {function1,function2} = require(‘modules’)