[Javascript] ES6 — Destructuring 解構賦值

Dosmanthus
5 min readJun 12, 2017

--

將陣列或物件中的資料取出成獨立變數。

Destructuring Objects 物件分離

const person = {
firstName: 'Peyton',
lastName: 'Chiang',
country: 'Taiwan',
city: 'Taipei',
}
const { firstName, lastName } = person;
  • Nested data
const peyton = {
firstName: 'Peyton',
lastName: 'Chiang',
links: {
social: {
twitter: 'https://twitter.com',
facebook: 'https://facebook.com',
},
web: {
blog: 'https://medium.com/@dd0425'
}
}
}
const { twitter, facebook:fb } = peyton.links.social;
// renaming facebook to fb
console.log(fb);
//
https://facebook.com
  • With default

如果有指派會取代預設值,沒有則使用預設值

const settings = { width: 300, color: 'red' };const { width = 100, height = 100, color = 'black', fontSize = 16 } = settings;
  • With variable renaming and default values
const { w: width = 100, h: height = 100 } = { w: 800 }

Destructing Arrays 陣列分離

const details = ['peyton chiang', 'female', 18];
const [name, gender, age] = details;
// 解構逗號分隔的字串
const data = 'Basketball, Sports, 1918, 34, peyton, 18';
const newData = data.replace(/\s+/g, '');
const [itemName, category, year, number] = newData.split(',');
// Rest parameters(其餘參數)
const team = ['Peyton', 'Penguin', 'Toby', 'Nicole'];
const [captain, assistant, ...members] = team;

Swapping Variables 變數交換

兩個變數可以透過一個解構指派式交換。沒有解構指派式時,則需要一個暫存變數來達成。

var a = 1;
var b = 3;

[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1

Destructing Functions 函數回傳值分離

  • 解析自函式回傳的陣列
function f() {
return [1, 2];
}

var a, b;
[a, b] = f();
console.log(a); // 1
console.log(b); // 2

忽略某些回傳值

function f() {
return [1, 2, 3];
}

var a, b;
[a, , b] = f();
console.log(a); // 1
console.log(b); // 3
  • 解析自函式回傳的物件
function convertCurrency(amount) {
const converted = {
USD:
amount * 0.76,
GPB:
amount * 0.53,
AUD:
amount * 1.01,
MEX:
amount * 13.30
};
return
converted;
}
const {MEX, AUD, USD} = convertCurrency(100);
console.
log(USD); // 76
  • Named defaults
function tipCalc(total, tip = 0.15, tax = 0.13) {
return
total + (tip * total) + (tax * total);
}

爲了使原本函數的參數不用依照順序給入,可以使用解構賦值。

當我們改爲傳入一個物件時,它會將物件解構成參數

function tipCalc({total = 100, tip = 0.15, tax = 0.13}) {
return
total + (tip * total) + (tax * total);
}
const bill = tipCalc({tax: 0.15, total: 200});
console.
log(bill);

需要注意的是,當沒有傳入任何參數會出現錯誤

const bill = tipCalc();
console.
log(bill);
//
Uncaught TypeError: Cannot match against 'undefined' or 'null'.

需指派預設的物件

function tipCalc({total = 100, tip = 0.15, tax = 0.13} = {}) {
return
total + (tip * total) + (tax * total);
}

參考:

--

--

No responses yet