倘若A代表人生的成功,那么公式是:A =X+Y+Z。X是工作,Y是游戏,z是保持缄默。——(美)爱因斯坦
我们以前从一个数组中获取第一项,可能是如下写法:
1 2
| let list = [1,2,3] let i = list[0]
|
有了解构赋值,可以如下写法:
1 2
| let list = [1,2,3] let [i] = list
|
如果稍微复杂点,例如下面这样从对象中取出来数组:
1 2
| let ruben = {hobby:['anime']} let favorite = ruben.hobby[0]
|
就可以写成:
1 2
| let ruben = {hobby:['anime']} let {hobby:[favorite]} = ruben
|
如果再复杂点
1 2 3
| let ruben = {hobby:['anime']} let achao = {favorite:undefined} achao.favorite = ruben.hobby[0]
|
可以写成
1 2 3
| let ruben = {hobby:['anime']} let achao = {favorite:undefined} [achao.favorite] = ruben.hobby
|
以及
1 2 3
| let ruben = {hobby:['anime']}; let achao = {favorite:undefined}; ({hobby:[achao.favorite]} = ruben);
|
关键在于,两边的结构要一致,而且不能使用{}
作为代码开头,会被解析为代码块
我们最后来一个收尾
1 2 3 4
| let ruben = {hobby:[{english:'ruben',chinese:'阿超',behavior:()=>'看动漫'}]}; let achao = {weekend:{todo:undefined},names:[]}; achao.weekend.todo = ruben.hobby[0].behavior; achao.names = [ruben.hobby[0].english,ruben.hobby[0].chinese];
|
写成:
1 2 3
| let ruben = {hobby:[{english:'ruben',chinese:'阿超',behavior:()=>'看动漫'}]}; let achao = {weekend:{todo:undefined},names:[]}; ({hobby:[{english:achao.names[0],chinese:achao.names[1],behavior:achao.weekend.todo}]} = ruben);
|