• TS学习之解构与展开


    一、解构

    1.解构数组

    let input = [1, 2];
    let [first, second] = input;
    console.log(first); // outputs 1
    console.log(second); // outputs 2

     a) 运用于函数

    function f([first, second]: [number, number]) {
        console.log(first);
        console.log(second);
    }
    f([6,8]);  
    //6
    //8

    b) 剩余语法 ...(注意...之前的空格)

    let [one, ...rest] = [1,2,3,4,5,6];
    console.log(one);   //1
    console.log(rest)   //[2,3,4,5,6]
    
    let [first] = [1,2,3,4,5,6]
    console.log(first)  //1
    
    let [,two,,four] = [1,2,3,4];
    console.log(two)    //2
    console.log(four)   //4

    2.对象解构

    let o = {
        a: "foo",
        b: 12,
        c: "test"
    }
    let { a, b } = o;
    console.log(a)  //"foo"
    console.log(b)  //12

    a)  剩余语法 ...

    let o = {
        a: "foo",
        b: 12,
        c: "test"
    }
    let { c, ...rest } = o;
    console.log(c);  //"test"
    console.log(rest)   //{ a: 'foo', b: 12 }

    b)运用于函数

    type C = { a: string, b?: number }
    function f({ a, b }: C): void {
        // ...
    }

    二、展开

    它允许你将一个数组展开为另一个数组,或将一个对象展开为另一个对象。

    let a1 = ["aa", "bb"];
    let a2 = [0, 1];
    let a3 = ["a", ...a1, "m", ...a2];
    console.log(a3) //[ 'a', 'aa', 'bb', 'm', 0, 1 ]
    
    let o1 = { name: "test", age: 20 };
    let o2 = { ...o1, height: 180 }
    console.log(o2);    //{ name: 'test', age: 20, height: 180 }
  • 相关阅读:
    网易企业免费邮箱
    168. Excel Sheet Column Title
    167.Two Sum II-Input array is sorted
    166. Fraction to Recurring Decimal
    165 Compare Version Numbers
    164. Maximum Gap
    163.Missing Ranges
    162.Find Peak Element
    161.One Edit Distance
    160. Intersection of Two Linked Lists
  • 原文地址:https://www.cnblogs.com/sghy/p/7728007.html
Copyright © 2020-2023  润新知