首页 > 代码库 > es6 浅解“解构”

es6 浅解“解构”

先上一段代码,
{
function move({x: t = 0, y = 0, z = 3} = ‘111‘) {
return [x="x",t, y, 9, z];
}

console.log(move({x: 3, y: 8, z: 5})); // ["x",3, 8, 9, 5]
console.log(move({x: 3})); // ["x",3, 0, 9 ,3]
console.log(move({})); // ["x",0, 0, 9, 3]
console.log(move()); // ["x",0, 0, 9 ,3]

let [a, ...b] = move({x: 4});
console.log(a);//x
console.log(b);//[4,0,9,3]
}

如果能弄懂这个代码,基本了解到解构的精髓了。
知识点1:
数组的解构
下标取值
let [a,b]=[3,4];//a=3,b=4
等价于
let c=[3,4];
let a=c[0];
let b=c[1];

赋默认值
let [a=1,b]=[,4];//a=1,b=4
等价于
let c=[undefined,4];
let a,b=c[1];
if(c[0]===undefined){
  a=1;
}
注意:let [a=1,b]=[null,4];//a=null,b=4,只有c[0]为undefined未定义才赋默认值

其他
let [a,...b]=[1,2,3,4];//a:1,b:[2,3,4]
let [a,,b]=[1,2,3];//a:1,b:3
let [a,[b],c]=[1,[2,3],4];//a:1,b:2,c:4

报错
let [a]=1;//报错
let [a]=false;//报错
let [a]=NaN;//报错
let [a]=undefined;//报错
let [a]=null;//报错
let [a]={};//报错

对象解构
let {a,b}={a:1,b:2};//a=1,b=2
相当于
let c={a:1,b:2};
let a=c.a;
let b=c.b;
let {b,a}={a:1,b:2};//a=1,b=2,没有排序要求

let {a:t,b}={a:1,b:2};//t=1,b=2
相当于
let c={a:1,b:2};
let t=c.a;
let b=c.b;
*a为匹配模式,t为变量名称.

let {a:{b:{c},d:h,b},g:t}={a:{b:{c:1},d:2},f:3,g:4}//c=1,t=4,h=2,b={c:1};
相当于
let o={a:{b:{c:1},d:2},f:3,g:4};
let c=o.a.b.c;
let h=o.a.d;
let b=o.a.b;
let t=a.g;

*多重嵌套,规则一样"冒号前为匹配模式,冒号后为变量名"

let a;
({a}={a:3});
*必须加括号,因为每一行的首个字符如果为{,会被解析为块级作用域
let a={},b=[];
({c:a.pro,d:b[0],e:b[1]=4}={c:2,d:3});//a={pro:2},b=[3,4];
相当于
let a={},b=[],f={c:2,d:3};
a.pro=f.c;
b[0]=f.d;
b[1]=f.e;
if(b[1]===undefined){
  b[1]=4;
}

let {0:a,1:b}=[3,4]//a=3,b=4
*数组是特殊的对象


分析文章开始的move函数
function move({x: t = 0, y = 0, z = 3} = ‘111‘) {
return [x="x",t, y, 9, z];
}
等价于
function move(a){
  if(a===undefined) a=‘111‘;
  let t=a.x, y=a.y, z=a.z, x;
  if(t===undefined) t=0;
  if(y===undefined) y=0;
  if(z===undefined) z=3;
  if(x===undefined) x=‘x‘;
  return [x,t,y,9,z]
}

想要学习完整详细的es6解构知识点或es6技术,推荐阮一峰老师的es6教程。


es6 浅解“解构”