相見恨晚。
過去式
以往在對 array 或 object 取值都是像這樣:
array:
1 2 3 4
| const arr = [1, 2, 3] const n1 = arr[0] const n2 = arr[1] const n3 = arr[2]
|
object:
1 2 3 4 5 6 7 8
| const obj = { name: 'Peanu', age: 23, address: 'Taiwan', } const name = obj.name const age = obj.age const address = obj.address
|
現在式
解構的概念很簡單,就是用「對應」的方式來取值,一個變數都會對應到一個 key 或 value。
array:
1 2
| const arr = [1, 2, 3] const [n1, n2, n3] = arr
|
你可以想成是這樣的對應關係:
1
| const [n1, n2, n3] = [1, 2, 3]
|
object:
1 2 3 4 5 6
| const obj = { name: 'Peanu', age: 23, address: 'Taiwan', } const {name, age, address} = obj
|
你可以想成是這樣的對應關係:
1 2 3 4 5 6 7 8 9 10
| const obj = { name: 'Peanu', age: 23, address: 'Taiwan', } const { name age address } = obj
|
應該很直覺吧?
讓我們層層相疊
如果解構出來的值是一個 object,那一樣可以再對它解構:
1 2 3 4 5 6 7 8 9 10 11 12 13
| const obj = { name: 'Peanu', age: 23, address: 'Taiwan', wife: { name: 'PPB', age: 24, address: 'Taiwan', } } const { wife } = obj const { name } = wife console.log(name)
|
進階-物件的巢狀取值
知道一下就好,實務上應該是不常這樣用:
1 2 3 4 5 6 7 8 9 10 11 12
| const obj = { name: 'Peanu', age: 23, address: 'Taiwan', wife: { name: 'PPB', age: 24, address: 'Taiwan', } } const {wife: {name}} = obj console.log(name)
|
看不懂的話,改用對應的關係來看會好懂很多:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const obj = { name: 'Peanu', age: 23, address: 'Taiwan', wife: { name: 'PPB', age: 24, address: 'Taiwan', } } const { wife: { name } } = obj console.log(name)
|
但要注意一下,這種巢狀取值的方式只能取到最裡面那個,如果你這樣用的話會有錯誤:
1 2 3 4 5 6 7 8 9 10 11 12
| const obj = { name: 'Peanu', age: 23, address: 'Taiwan', wife: { name: 'PPB', age: 24, address: 'Taiwan', } } const {wife: {name}} = obj console.log(wife)
|
Array 當然也能這樣玩:
1 2
| const arr = [ 1, 2, [3, 4] ] const [n1, n2, [n3, n4]] = arr
|
在函式中解構
當 function 的預期的參數是 object,可以在定義的時候就先解構:
1 2 3 4 5 6 7 8 9 10 11
| function test({name, age, address}) { console.log(name) console.log(age) console.log(address) } let person = { name: 'PeaNu', age: 23, address: 'Taiwan' } test(person)
|
當 key / value 相等時可以縮寫
1 2 3 4 5 6 7
| const name='peanu', age=20, gender='man'; const obj = { name, age, gender } console.log(obj)
|
解構出來的東西可以重新命名
1 2 3 4 5 6 7 8 9 10 11 12
| const obj = { name: 'peanu', age: 25, gender: 'man' }
const {name, age , gender} = obj
const {name: peanuName, age: peanuAge , gender: peanuGender} = obj
console.log('A:', name, age , gender) console.log('B:', peanuName, peanuAge , peanuGender)
|
陣列的應用:交換
舉個爛例子,假設沒有下雨,我就午餐吃牛肉麵,晚餐吃咖哩飯;反之就倒過來。
但這個技巧是運用變數名稱來替換,並不是真正意義上的那種交換(換位置)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| let isRaining = false function whatDoYouEatToday(condition) { const meals = ['牛肉麵', '咖哩飯'] if(!condition) { const [lunch, dinner] = meals console.log(`午餐-->${lunch},晚餐-->${dinner}`) } else { const [dinner, lunch] = meals console.log(`午餐-->${lunch},晚餐-->${dinner}`) } } whatDoYouEatToday(isRaining)
|