前言
解構賦值是 ES6 新增語法糖,若要使用陣列、物件中的值,來見新的變數/常數,可以使用解構賦值的方法,來快速建立。
陣列解構
陣列解構主要是根據陣列中的順序,再對應的順序建立變數/常數,便可直接獲得陣列中的值。
比如過去要獲得陣列的值會這樣寫:
1 2 3
| const array = [1,2] const a = array[0] const b = array[1]
|
而現在可使用解構:
1 2
| const [a,b] = [1,2] console.log(a, b)
|
關於陣列解構還有其他特殊用法,這邊舉出幾個較容易使用到的:
1 2 3 4 5 6 7 8 9 10 11 12
| let a, b [a, b] = [1,2] console.log(a,b)
const [ a, b, ...c ] = [1,2,3,4,5] console.log(a,b)
const [a, ,c] = [1,2,3] console.log(a,c)
|
物件解構
物件要使用解構會和陣列不同,陣列主要是按照順序獲得值,而物件要使用解構則是要讓,變數名稱和物件屬性一致才可以取得物件的值,比如:
1 2 3 4 5 6 7 8
| const school = { name:'Taipei University', classes: { teacher: 'Alex', student:['Kevin','Clara','Rose'] }, } const { teacher, student } = school.classes
|
上面範例就是透過解構,直接將 school.classes
中的 teacher
、 student
屬性中的值變成對應的常數,由於我們現在很常會使用到 Ajax 來獲得後端傳來的物件,因此這個寫法使到頻率其實滿高的,而當然物件解構也有一些特殊用法,這邊舉出幾個較容易使用到的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
const school = { name:'Taipei University', classes: { teacher: 'Alex', student:['Kevin','Clara','Rose'] }, } const { name: schoolName } = school console.log(schoolName)
const obj = { a:1, b:2, c:3, d:4, e:5 } const { a,b,...arg } = obj console.log(a,b,arg)
const school = { name:'Taipei University', classes: { teacher: 'Alex', student:['Kevin','Clara','Rose'] }, } function getTeacher({ classes : { teacher }}){ return teacher } console.log(getTeacher(school))
|
解構賦值預設值
而解構賦值其實也和函式參數一樣,也能設定預設值,不論是物件見或是陣列,都可以使用 =
運算子,為解構賦值新增的變數/常數 設定預設值,以避免解構賦值時沒有正確獲得值。
1 2 3 4 5 6 7 8 9 10 11 12
| const [a, b, c = 3] = [1, 2] console.log(a, b, c) const school = { name:'Taipei University', classes: { teacher: 'Alex', student:['Kevin','Clara','Rose'] }, } const { teacher ,student , address = '新北市三峽區大學路151號' } = school.classes
|
參考文獻