JavaScript 解構賦值(Destructuring Assignment)教學
解構賦值是一種簡潔的語法,能從陣列或物件中提取值並賦予變數。
🔹 1. 陣列解構
const arr = ["Alice", 30, "Taipei"];
const [name, age, city] = arr;
console.log(name); // Alice跳過元素
const [first, , third] = [1, 2, 3];
console.log(third); // 3剩餘元素
const [head, ...rest] = [10, 20, 30, 40];
console.log(rest); // [20, 30, 40]🔹 2. 物件解構
const person = {
name: "Ben",
age: 25,
city: "Kaohsiung"
};
const { name, age } = person;
console.log(name); // Ben更名變數
預設值
🔹 3. 解構用於函式參數
🔹 4. 巢狀解構
解構賦值可以讓程式碼更簡潔直觀,是 ES6 中非常常用的語法,尤其在處理物件或 API 回傳資料時非常有用。
Last updated