[TOC]
## 解構賦值
### 對象解構和數組解構的不同之處
- 數組解構若出現缺省需要解構占位
```
let [,,x] = [1,2,3];
//而對象解構因為存在鍵名所以不需要
```
- 數組解構和對象解構都可以設置默認值,另外對象解構可以設置別名
>[danger] **注意**:等號為默認值,冒號為取別名
```
let [a = "a", b = "b", c =new Error('C必須指定')] = [1, , 3];
//用冒號給對象的鍵名取個別名,且原先名字不再能用
let {name:diyName} = {name:'abc'};
console.log(diyName); //abc
//對象解構默認值
s({}); //1
function s({a='1',b='2',c='3'}){
console.log(a); //1
}
let {a=1,b=2,c=3} = {};
console.log(a); //1
console.log(b); //2
//數組成員木有鍵名,數組解構相當于就是給成員取了個別名
let [a,b,c] = [1,2,3];
console.log(a); //1
console.log(b); //2
```
### 解構參數
```
let destruct = function({name,age}){
console.log(name,age);
}
destruct({name:'ff',age:1});
```
### 嵌套賦值
重點在于神似
```
let [x, [y], z] = [1, [2.1, 2.2]];
console.log(x, y, z);
let [x, [y,z]] = [1, [2.1, 2.2]];
console.log(x,y,z);
let [json,arr,num] = [{name:'ff'},[1,2],3];
console.log(json,arr,num);
```
### 基本類型的結構賦值
```
let {length:len} = 'hello';
//String.prototype.length
console.log(len); //5
let [a,b,c,d] = '1234';
console.log(a,b,c,d); //1 2 3 4
let {toString:ts} = 1;
let {toString:ts2} = true;
console.log(ts); //function toString(){[natvie code]}
console.log(ts2); //function toString(){[natvie code]}
//Num.prototype.toString
```
## 展開操作符
```
// 可以替代concat
var arr1 = [1, 3];
var arr2 = [3, 5];
var arr3 = arr1.concat(arr2);
var arr4 = [...arr1, ...arr2];
// 可以替代apply
var m1 = Math.max.apply(null, [8, 9, 4, 1]);
var m2 = Math.max(...[8, 9, 4, 1]);
//傳入參數
let print = function(a,b,c){
console.log(a,b,c);
}
// print([1,2,3]);
print(...[1,2,3]);
//類數組的轉數組
function max(a,b,c) {
console.log(Math.max(...arguments));
}
max(1, 3, 4);
```
## 剩余運算符
剩余操作符可以把其余的參數的值都放到數組里面
```
let rest = function(a,...rest){
console.log(a,rest);
}
rest(1,2,3);
```