0%

ES6-解構賦值

陣列解構

一般來說要將陣列中的值取出來,並且放置在其他變數中,都必須利用下變的方法

1
2
3
const nums = [ 1, 2]
const first = nums[0]
const second = nims[1]

而在ES6中使用簡單一行就可以完成

1
2
const nums = [ 1, 2]
const [ first, second] = nums

或是

1
2
3
4
const nums = [ 1, 2]
let first;
let second;
[ first, second] = nums

預設值

若需要再新增一個third的變數呢?因為目前nums裡面只有兩筆資料,第三筆就會為空,這時候我們就可以讓它在沒有對應值得時候,給予一個預設值

1
2
const nums = [ 1, 2]
const [ first, second, third = 3] = nums

忽略元素

若想忽略其中幾個元素呢?假設目前nums裡有三筆資料,只要拿第一筆跟第三筆的話,就可以利用忽略元素的方法忽略掉中間的元素

1
2
const nums = [ 1, 2, 3]
const [ first, , third] = nums

剩餘部分

若要將陣列拆成一個變數與一個陣列,就可以透過剩餘部分來撰寫

1
2
3
4
const nums = [ 1, 2, 3, 4]
const [ first, ,...others] = nums
//first ===1
//other ===[2,3,4]

變數轉換

過去若想要讓變數交換的話,通常都會利用以下方法

1
2
3
4
5
let a = 1
let b = 2
let tmp = a
a = b
b = tmp

在這邊可以利用下面的方法快速的將變數交換

1
2
3
let a = 1
let b = 2
[a, b] = [b, a]

物件解構

陣列可以透過解構的方式將裡面的值取出來,物件也可以將屬性取出來,但物件是透過大括號{}的方式來進行,要記得解構的時候,提取的數值名稱,必須與物件屬性名稱相同

1
2
3
4
5
6
const point = {
x:150,
y:150,
}

const { x, y} = point;

預設值

若物件缺少屬性,就可以先用預設值替代

1
2
3
4
5
const point = {
y:150,
}

const { x = 100, y} = point;

指派新名稱

可以將物件取出來的屬性重新命名,只有物件才有這個功能,陣列沒有

1
2
3
4
5
6
const point = {
x:150,
y:150,
}

const { x:px, y:py} = point;

解構函式參數

一般要將物件傳入函式中並且利用物件中的屬性進行計算,都必須如下方所示

1
2
3
4
5
const point={ x:5, y:2}

function distance(point){
return Math.sqrt(point.x*point.x+point.y*point.y)
}

透過解構函式參數,可以直接在函式中將物件進行解構,將屬性值挑出來存入變數中,並且進行計算

1
2
3
4
5
6
const point={x:5,y:2}

function distance(point){
const { x, y} = point
return Math.sqrt(x*x+y*y)
}

也可以在函式宣告時就在傳入值那邊進行解構

1
2
3
4
5
const point={x:5,y:2}

function distance({ x, y}){
return Math.sqrt(x*x+y*y)
}

若傳入的物件中可能缺乏某個屬性,可以在解構時預設屬性

1
2
3
4
5
const point={y:2}

function distance({ x=0, y}){
return Math.sqrt(x*x+y*y)
}