数组结构

  • 数组每一项对应解构
    1. var arr: [number, number] = [1, 2];
    2. function fn1([a, b]: [number, number]) {
    3. console.log(a, b);
    4. }
    5. fn1(arr);
  • 数组剩余项解构
  1. const arr2 = [1, 2, 3, 4, 5];
  2. let [a, ...res] = arr2;
  3. console.log(a, res); // [2,3,4,5]
  • 数组某几项解构
  1. let [, second, ...res2] = arr2;
  2. console.log(second, res2); // 2,[3,4,5]

对象解构

  • 属性一一对应解构
  1. const obj = {
  2. k1: 1,
  3. k2: 'hello',
  4. k3: false,
  5. };
  6. let { k1, k2 } = obj;
  • 解构剩余属性
  1. const obj2 = {
  2. f1: 1,
  3. f2: 'hello',
  4. f3: false,
  5. };
  6. // fs:所有其他属性集合的对象
  7. let { f1, ...fs } = obj2;
  • 重命名
  1. const obj3 = {
  2. e1: 1,
  3. e2: 'hello',
  4. };
  5. // 这样写可能会与ts类型声明混淆
  6. let { e1: newName } = obj3;
  7. // 等同于
  8. const newName2 = obj3.e2; // hello
  9. console.log(newName, newName2); // 1
  1. // 不要滥用解构表达式,以下例子:默认值i,其实没有用,因为必须传入有属性值i的对象
  2. function test3({ i, j = 1000 } = { i: 1 }) {
  3. console.log(i, j);
  4. }
  5. const obj6 = {
  6. i: 10,
  7. };
  8. test3(obj6);
  • 函数参数解构和默认值
  1. function test2({ i, j = 'xxx' }: { i: number; j?: string }) {
  2. console.log(i, j);
  3. }

展开

数组展开

  1. var arr1 = [1, 2, 3];
  2. var arr2 = [4, 5, 6];
  3. var arr3 = [0, ...arr1, 3.5, ...arr2, 7, 8];

对象展开

注意顺序,右边的会覆盖左边的

  1. const obj = {
  2. a: 1,
  3. b: 2,
  4. c: 3,
  5. };
  6. const obj2 = { d: 4, ...obj };
  7. console.log(obj2);
  8. // 右边的会覆盖左边的
  9. const obj3 = { d: 4, ...obj, a: 100 };
  10. console.log(obj3);