数组结构
- 数组每一项对应解构
var arr: [number, number] = [1, 2];function fn1([a, b]: [number, number]) {console.log(a, b);}fn1(arr);
- 数组剩余项解构
const arr2 = [1, 2, 3, 4, 5];let [a, ...res] = arr2;console.log(a, res); // [2,3,4,5]
- 数组某几项解构
let [, second, ...res2] = arr2;console.log(second, res2); // 2,[3,4,5]
对象解构
- 属性一一对应解构
const obj = {k1: 1,k2: 'hello',k3: false,};let { k1, k2 } = obj;
- 解构剩余属性
const obj2 = {f1: 1,f2: 'hello',f3: false,};// fs:所有其他属性集合的对象let { f1, ...fs } = obj2;
- 重命名
const obj3 = {e1: 1,e2: 'hello',};// 这样写可能会与ts类型声明混淆let { e1: newName } = obj3;// 等同于const newName2 = obj3.e2; // helloconsole.log(newName, newName2); // 1
// 不要滥用解构表达式,以下例子:默认值i,其实没有用,因为必须传入有属性值i的对象function test3({ i, j = 1000 } = { i: 1 }) {console.log(i, j);}const obj6 = {i: 10,};test3(obj6);
- 函数参数解构和默认值
function test2({ i, j = 'xxx' }: { i: number; j?: string }) {console.log(i, j);}
展开
数组展开
var arr1 = [1, 2, 3];var arr2 = [4, 5, 6];var arr3 = [0, ...arr1, 3.5, ...arr2, 7, 8];
对象展开
注意顺序,右边的会覆盖左边的
const obj = {a: 1,b: 2,c: 3,};const obj2 = { d: 4, ...obj };console.log(obj2);// 右边的会覆盖左边的const obj3 = { d: 4, ...obj, a: 100 };console.log(obj3);
