解構賦值 Destructuring Assignment


Posted by Calon on 2022-04-26

解構賦值是 ES6 的語法糖,它可以縮短程式碼並且增加可閱讀性。

陣列解構

在以前要將陣列中的值取出來並賦予到其他變數上時,會這樣寫:

const ary = [1, 2, 3];
const a = ary[0];
const b = ary[1];
const c = ary[2];


數量一多時寫起來很麻煩,看起來也不是很好閱讀,而解構賦值可以幫我們解決這個問題。
在撰寫的時候如同上面所介紹解構賦值像是鏡子般將左邊對應右邊,所以在陣列使用時左邊的順序會對應右邊的順序。

const [a, b, c] = [1, 2, 3]; // a=1 b=2 c=3

// 也可以直接代變數
const ary = [1, 2, 3];
const [a, b, c] = ary; // a=1 b=2 c=3


而當對應到的值是空值時,則會回傳 undefined

const [a, b, c] = [1, 2]; // a=1 b=2 c=undefined


如果想要選取特定位置的值,只需要將前面的變數空著。

const [, , a] = [1, 2, 3, 4]; // a=3


也可以用於交換變數裡面的值,在一次交換多個變數時很方便。

let banana = '香蕉';
let papaya = '木瓜';
let apple = '蘋果';
[banana, papaya, apple] = [apple, banana, papaya];
// banana '蘋果'
// papaya '香蕉'
// apple '木瓜'


如果代入字串則會拆解成一個個字元。

const [a, b, c] = '好棒棒'; // a='好' b='棒' c='棒'


你也可以將複雜的多維陣列拆解到想要賦予的變數上:

const [a, [b, , [c, d]], e] = 
  ['最外層1', ['最二層1', '最二層2', [['最深層1', '最深層2'], '最三層']], '最外層2'];
// a='最外層1' b='最二層1' c=['最深層1', '最深層2']
// d=最三層 e=最外層2


結合其餘參數

如果想將陣列中的其中幾個資料個別賦予到變數上,而剩下的資料組成一個陣列,可以結合運用其餘參數

const [a, ...others] = [1, 2, 3]; // a=1 others=[2, 3]


物件解構

在物件解構中因為物件沒有索引值,在此是用屬性名稱來做對應,並且沒有順序性。所對應的屬性名稱會是變數名稱。

const obj = {
    dog: 'kick',
    person: 'calon',
    child: 'john'
};

const {person} = obj; // person='calon'

const {dog, child} = obj; // dog='kick' child='john'dog

如果想要改變數名稱,只要在屬性名稱後面加上 :,然後在後面加上想要的變數名稱就行了。

const obj = {
    dog: 'kick',
    person: 'calon',
    child: 'john'
};

const {person:classmate} = obj; // classmate='calon'
const {dog:pet, child} = obj; // pet='kick' child='john'


陣列與物件混合使用

遇到陣列與物件混合的情況,只要照著上述的觀念也能輕鬆的將想要的值解構出來:

const obj = {
    dogs: ['kick', 'kuro', 'muji'],
    parents: ['miya', 'bob'],
    child: 'john'
};

const {dogs: [ , ...dogs], parents: [mom, dad], child} = obj; 
// dogs=['kuro', 'muji'] mom='miya' dad='bob' child='john'


預設值

為了避免碰到沒有值而回傳 undefined 的狀況,我們可以使用 ES6 新增的預設值來避免:

const [a = 1, b = 2] = [3]; // a=3 b=2

const {breakfast = 'onigiri', lunch = 'noodle', dinner = 'salad'} = 
      {
          breakfast: 'hamburger',
          dinner: 'rice'
      }; // breakfast='hamburger' lunch='noodle' dinner='rice'


應用在 function 參數

我們也可以在 function 的參數上解構賦值使用,方式和前面所介紹的一樣,陣列對應順序,物件則對應變數名稱。

function addUp([a = 0, b]){
    return a + b;
};
addUp([]); // NaN
addUp([3, 4]); // 7
addUp(); // Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))

function showName({teacher = 'bob', student}){
    return `teacher is ${teacher}, and student is ${student}.`;
};

showName(); // Uncaught TypeError: Cannot destructure property 'teacher' of 'undefined' as it is undefined.
showName({}); // 'teacher is undefined, and student is bob.'
showName({teacher:'miya'}); // 'teacher is miya, and student is bob.'
showName({mom:'miya'}); // 'teacher is undefined, and student is bob.'

參考資料

#javascript #ES 6







Related Posts

網站部屬

網站部屬

2. SpringBoot使用jms整合IBM MQ

2. SpringBoot使用jms整合IBM MQ

Secure Apache Using Certbot with Let's Encrypt on Ubuntu 20.04

Secure Apache Using Certbot with Let's Encrypt on Ubuntu 20.04


Comments