JavaScript-解構賦值

解構賦值是什麼?

解構賦值 (Destructuring assignment) 語法是一種 JavaScript 運算式,用以拆解物件與陣列中的資料成為獨立變數。

使用方式

  1. 陣列解構

    用新的陣列變數[White, Red, Yellow] 將 flowers 陣列裡的值分別指派給 White、Red、Yellow 變數,此時 White = Lily, Red = Rose, Yellow = Sunflower。

    const flowers = ["Lily", "Rose", "Sunflower"];
    const [White, Red, Yellow] = flowers;
    console.log(White); //Lily
    console.log(Red); //Rose
    console.log(Yellow); //Sunflower
    

    可簡化為

    const [White, Red, Yellow] = ["Lily", "Rose", "Sunflower"];
    console.log(White, Red, Yellow); //Lily Rose Sunflower
    

    也可以只取其中一個值,以下為例取出第一個值

    const [White] = ["Lily", "Rose", "Sunflower"];
    console.log(White); //Lily
    

    還可以用逗號來略過不要的值,逗點位置需注意

    const [, Yellow] = ["Lily", "Rose", "Sunflower"];
    console.log(Yellow); //Rose
    
    const [ , , Yellow] = = ["Lily", "Rose", "Sunflower"];
    console.log(Yellow); //Sunflower
    

    用…可以將陣列再分陣列

    const [White, ...Red] = ["Lily", "Rose", "Peony"];
    console.log(White, Red); //Lily [ 'Rose', 'Peony' ]
    
  2. 物件解構

    我有一個 flowers 物件具有三個鍵值,但我只要其中的 Lily 和 Rose

    const flowers = {
      Lily: "White",
      Rose: "Red",
      Sunflower: "Yellow",
    };
    const { Lily, Rose } = flowers;
    console.log(Lily, Rose); //White Red
    

    可以將物件當作函式的參數提取某屬性的值

    function bmi(someone) {
      const { height, weight } = someone; //解構
      console.log(height); // 170
      console.log(weight); //70
    }
    const Bill = {
      height: 170,
      weight: 70,
      age: 20,
    };
    bmi(Bill);
    

    還可以再更簡化

    function bmi({ height, weight }) {
      console.log(height, weight); // 170 70
    }
    const Bill = {
      height: 170,
      weight: 70,
      age: 20,
    };
    bmi(Bill);
    

    也可以處理物件巢狀結構,使用雙重大括號{}以及冒號:將函式的參數修改如下:

    function bmi({ name: { firstname } }) {
      console.log(firstname); //Bill
    }
    const person = {
      name: {
        firstname: "Bill",
        lastname: "Wilson",
      },
      height: 170,
      weight: 70,
      age: 20,
    };
    bmi(person);
    
comments powered by Disqus