ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构 | ||
---|---|---|
以前,为变量赋值,只能直接指定值。
let x=1;
let y=2;
let z=3;
ES6允许如下写法 let[x,y,z]=[1,2,3];//模式匹配,按照位置来匹配 let [x,y,z]=[1,[1,2],3];
let [x,y,z]=[1,{'x':123},3];
console.log(y);
//输出依次是 2
[1,2] {x: 123}
let [head,...tail] = [0,1,2,3,4,5,6,7,8,9];
console.log(head);
//0
console.log(tail);
//[1,2,3,4,5,6,7,8,9]
解构不成功,值都会等于
上面两个案例都属于不完全解构,但可以成功 如果等号右边不是数组,就会报错
上面的语句都会报错,因为等号右边的值,要么转为对象以后不具备 Iterator 接口(前五个表达式),要么本身就不具备 Iterator 接口(最后一个表达式)。
解构赋值,允许指定默认值
数组:按照位置来匹配
let [x,y='3',z]=[1];
let [x,y='3',z]=[1,2];
let [x,y='3',z]=[1,2,3];
let [x,y='3',z]=[1,,3];
let [x,y='3',z='4']=[1,,null];
console.log(x,y,z);
//1 3 undefined
//1 2 undefined
//1 2 3
//1 "3" 3
//1 "3" null
函数
function f(){
return 'aaa';
};
let[x=f()]=[];
console.log(x);
//'aaa'
对象 按照对应的名字(属性的名称)来匹配
let{x,y}={x:"1",y:"2"};==let{x:x,y:y}={x:"1",y:"2"} x:x 前面的x代表一个匹配模式,后者代表一个变量 console.log(x,y);//这里的x,y为后面的变量 1 2
let {x1:qq,y1}={y1:'22',x1:'21'};
console.log(qq);
//21
let {x1:qq,y1}={y1:'22',x1:'21'};
console.log(x1);//报错
let {x=1,y}={x:'a'};
console.log(x,y);//a undefined
let {x : y ='111'}={x : undefined};
console.log(y);//111
let {x : y ='111'}={x : null};
console.log(y);//null
字符串的结构赋值
let [a,b,c,d,e,f]='nodejs';
console.log(b);//o
类似于数组,按照位置赋值
函数参数的解构赋值
function fun([x,y]){
return x+y;
};
fun([3,5]);//8
function fun([x=0,y=0]){
return x+y;
};
fun([]);
//0
function fun([x=0,y=0]){
return x+y;
};
fun([3,5]);
//8
function fun([x=3,y=5]){
return x+y;
};
fun([]);
//8
如果调用的时候传值就用次值,否则会直接使用默认值 函数里返回多个值 function fun(){ return [1,2,3]; } let [a,b,c]=fun(); console.log(a,b,c);//1,2,3
//对象
function num(){
let obj={
"name":"str",
"age":12
}
return obj
}
let [name:wqw,age]=num();
console.log(wqw,age);
let obj={
"name":"str",
"age":12,
"friends":["a1","b1"],
"member":{x:1,y:2}
}
let {name,age,friends:ff,member}=obj;
console.log(ff[1]);
//b1
console.log(member.x);//1
上面代码交换变量 (2)从函数返回多个值 函数只能返回一个值,如果要返回多个值,只能将它们放在数组或对象里返回。有了解构赋值,取出这些值就非常方便。
(3)函数参数的定义 解构赋值可以方便地将一组参数与变量名对应起来。
(4)提取 JSON 数据 解构赋值对提取 JSON 对象中的数据,尤其有用。
上面代码可以快速提取 JSON 数据的值。 (5)函数参数的默认值
指定参数的默认值,就避免了在函数体内部再写 (6)遍历 Map 结构 任何部署了 Iterator 接口的对象,都可以用
如果只想获取键名,或者只想获取键值,可以写成下面这样。
(7)输入模块的指定方法 加载模块时,往往需要指定输入哪些方法。解构赋值使得输入语句非常清晰。
|
ES6新特性:解构赋值
猜你喜欢
转载自blog.csdn.net/chenacxz/article/details/79819112
今日推荐
周排行