Javascript 的 解構賦值 ( Destructuring Assignment ) Cheat Sheet

邱秉誠
3 min readMay 25, 2024

--

解構賦值 是 JavaScript 中的一種語法,允許使用者從陣列或物件中提取屬性值,並將其賦值給變量。每次都還要上網搜尋使用方法有點麻煩,以下整理各種解構賦值的方法供快速查詢。

變數交換

// 兩個變數交換
let a = 1;
let b = 3;
[a, b] = [b, a];

// 陣列內元素交換
const arr = [1, 2, 3];
[arr[2], arr[1]] = [arr[1], arr[2]];

對陣列提取屬性

// 從陣列中提取值並賦值給變數
const fruits = ['Apple', 'Banana', 'Cherry'];
const [first, second, third] = fruits;

// 從函示回傳陣列提取值
function f() {
return [1, 2];
}

let a, b;
[a, b] = f();

// 解構時跳過某些元素
const fruits = ['Apple', 'Banana', 'Cherry'];
const [first, , third] = fruits;
const [, ...rest] = numbers;

// 使用解構賦值提取並更新變數
let numbers = [1, 2, 3, 4, 5];
let [first, second, ...rest] = numbers;
[first, second] = [10, 20];

對物件提取屬性

// 從物件提取值並賦值給變數
const person = {
name: 'Alice',
age: 25,
city: 'New York'
};
const { name, age, city } = person;

// 給變數不同名字
const person = {
name: 'Alice',
age: 25,
city: 'New York'
};

const { name: personName, age: personAge, city: personCity } = person;

// 為變數設定預設值
const person = {
name: 'Alice',
age: 25
};

const { name, age, city = 'Unknown' } = person;

// 從深層嵌套提取值
const person = {
name: 'Alice',
age: 25,
address: {
city: 'New York',
zip: '10001'
}
};

const { name, address: { city, zip } } = person;

// 移除第一個屬性
// 使用解構賦值移除 'name' 屬性
const person = {
name: 'Alice',
age: 25,
city: 'New York'
};

const { name, ...rest } = person;

// 更新對象的屬性
let person = {
name: 'Alice',
age: 25,
city: 'New York'
};

person = { ...person, age: 30, city: 'San Francisco' };

參考資料

--

--

邱秉誠
邱秉誠

Written by 邱秉誠

畢業於台大工業工程所,目前任職於台積電。

No responses yet