紀錄工作經驗、相關知識,解決技術相關問題。

Javascript

JS 解構賦值(destructuring):陣列與物件的用法

JS 解構賦值(destructuring):陣列與物件的用法 特色圖片

JS 解構賦值(destructuring assignment)是把陣列的元素或物件的屬性,一次取出並放進多個獨立變數的語法。MDN 稱它為 destructuring,繁中版譯為「解構」,搜尋時常見「解構賦值」的說法,指的是同一個語法。

const [first, second] = ["one", "two"];
const { id, name } = { id: 42, name: "Amy" };

console.log(first, second);   // one two
console.log(id, name);        // 42 Amy

解構的寫法和建立陣列、物件的字面值很像,只是放在賦值的左邊,做的是反向的事:陣列字面值把變數收進陣列,陣列解構則把陣列的元素分給各個變數。

兩種寫法:宣告與賦值

依 MDN 說明,解構的樣式(pattern)分成兩種,語法稍有不同。

宣告樣式(binding pattern)以 var、let 或 const 開頭,每個項目都會綁定到一個新變數:

const obj = { a: 1, b: { c: 2 } };
const {
  a,
  b: { c: d },
} = obj;

console.log(a, d);   // 1 2

賦值樣式(assignment pattern)不以宣告關鍵字開頭,取出的值會指派給已存在的目標,例如先宣告好的變數,或另一個物件的屬性:

const numbers = [];
const obj = { a: 1, b: 2 };
({ a: numbers[0], b: numbers[1] } = obj);

console.log(numbers);   // [ 1, 2 ]

物件解構沒有宣告關鍵字時,整個運算式要用小括號包起來。{ a, b } = ... 單獨寫在行首會被當成區塊,而不是物件字面值,是無效的語法:

let a, b;

({ a, b } = { a: 1, b: 2 });
console.log(a, b);   // 1 2

try {
  new Function("let a, b; { a, b } = { a: 1, b: 2 };");
} catch (e) {
  console.log(e.name);   // SyntaxError
}

賦值樣式只能搭配單純的賦值運算子(=),不能用在 +=、*= 這類複合賦值運算子。

補充說明:同一個宣告的所有變數共用同一個關鍵字。想讓部分變數可重新賦值、另一部分唯讀時,MDN 建議分成兩次解構,一次用 let、一次用 const。

陣列解構

基本用法與略過元素

陣列解構依位置對應:第一個變數取第一個元素,第二個變數取第二個元素。要略過某個元素,就在該位置留空:

const foo = ["one", "two", "three"];

const [red, yellow, green] = foo;
console.log(red, yellow, green);   // one two three

const [a, , c] = foo;
console.log(a, c);                 // one three

變數比元素多

左邊的變數數量比陣列元素多時,多出來的變數是 undefined:

const foo = ["one", "two"];

const [red, yellow, green, blue] = foo;
console.log(red);      // one
console.log(yellow);   // two
console.log(green);    // undefined
console.log(blue);     // undefined

解析函式回傳的陣列

函式回傳陣列時,用解構可以一行取出需要的值,不需要的用逗號略過:

function f() {
  return [1, 2, 3];
}

const [a, , b] = f();
console.log(a, b);   // 1 3

const [c] = f();
console.log(c);      // 1

交換變數

不用暫存變數,一個解構運算式就能交換兩個變數的值。陣列內的元素也能這樣交換:

let a = 1;
let b = 3;

[a, b] = [b, a];
console.log(a, b);   // 3 1

const arr = [1, 2, 3];
[arr[2], arr[1]] = [arr[1], arr[2]];
console.log(arr);    // [ 1, 3, 2 ]

解構任何可迭代物件

陣列解構使用的是可迭代協定(iterable protocol),所以不只陣列,任何可迭代的值都能解構,例如 Map:

const [a, b] = new Map([
  [1, 2],
  [3, 4],
]);

console.log(a, b);   // [ 1, 2 ] [ 3, 4 ]

沒有實作可迭代協定的值不能當陣列解構,會丟出 TypeError:

try {
  const obj = { 0: "a", 1: "b", length: 2 };
  const [a, b] = obj;
} catch (e) {
  console.log(e.name, "|", e.message);   // TypeError | obj is not iterable
}

錯誤訊息的文字依引擎而異,上面是 Node.js v22.20.0 的輸出。

可迭代物件只會迭代到所有變數都取到值為止。下面的迭代器有四個值,但只有兩個變數,所以只會跑到前兩個:

const obj = {
  *[Symbol.iterator]() {
    for (const v of [0, 1, 2, 3]) {
      console.log(v);
      yield v;
    }
  },
};

const [a, b] = obj;   // 只印出 0 和 1

物件解構

基本用法

物件解構依屬性名稱對應,變數名稱就是屬性名稱,順序不影響結果:

const user = {
  id: 42,
  isVerified: true,
};

const { id, isVerified } = user;

console.log(id);           // 42
console.log(isVerified);   // true

const { id } = user 等同 const id = user.id。

重新命名變數

屬性名稱和想用的變數名稱不同時,寫成「屬性名稱: 變數名稱」。冒號左邊是來源的屬性,右邊才是新變數:

const o = { p: 42, q: true };
const { p: foo, q: bar } = o;

console.log(foo);   // 42
console.log(bar);   // true

這裡 const { p: foo } = o 是從 o 取出屬性 p,放進名為 foo 的變數,p 本身不會成為變數。

屬性名稱不是合法的 JavaScript 識別字時,也要用這個寫法取出:

const foo = { "fizz-buzz": true };
const { "fizz-buzz": fizzBuzz } = foo;

console.log(fizzBuzz);   // true

預設值

每個解構的項目都能加預設值,寫在 = 後面。屬性不存在,或值是 undefined 時使用預設值;值是 null 不會使用:

const [a = 1] = [];
const { b = 2 } = { b: undefined };
const { c = 2 } = { c: null };

console.log(a);   // 1
console.log(b);   // 2
console.log(c);   // null

預設值可以是任何運算式,而且只有在需要時才會計算:

const { b = console.log("hey") } = { b: 2 };
// 不會印出任何東西,因為 b 已有值,不需要計算預設值

重新命名和預設值可以一起用,先寫新變數名稱,再接預設值:

const { a: aa = 10, b: bb = 5 } = { a: 3 };

console.log(aa);   // 3
console.log(bb);   // 5

計算屬性名稱

屬性名稱可以用方括號放運算式,和物件字面值的計算屬性名稱一樣:

const key = "z";
const { [key]: foo } = { z: "bar" };

console.log(foo);   // bar

原型鏈、原始值與 null

物件解構近似屬性存取,所以屬性不在物件自己身上時,會沿著原型鏈往上找:

const obj = {
  self: "123",
  __proto__: {
    prot: "456",
  },
};
const { self, prot } = obj;

console.log(self);   // 123
console.log(prot);   // 456

對原始值解構時,值會先被包成對應的包裝物件,再取屬性:

const { a, toFixed } = 1;

console.log(a);                  // undefined
console.log(typeof toFixed);     // function

null 和 undefined 不能解構,和存取屬性一樣會丟出 TypeError,即使左邊的樣式是空的也一樣:

for (const run of [
  () => { const { a } = undefined; },
  () => { const { b } = null; },
  () => { const {} = null; },
]) {
  try {
    run();
  } catch (e) {
    console.log(e.name, "|", e.message);
  }
}
// TypeError | Cannot destructure property 'a' of 'undefined' as it is undefined.
// TypeError | Cannot destructure property 'b' of 'null' as it is null.
// TypeError | Cannot destructure 'null' as it is null.

錯誤訊息的文字依引擎而異,上面是 Node.js v22.20.0 的輸出。

巢狀解構

陣列與物件可以任意巢狀。MDN 的範例從 translations 陣列的第一個物件取出 title,並重新命名避免和外層的 title 衝突:

const metadata = {
  title: "Scratchpad",
  translations: [
    {
      locale: "de",
      localizationTags: [],
      lastEdit: "2014-04-14T08:43:37",
      url: "/de/docs/Tools/Scratchpad",
      title: "JavaScript-Umgebung",
    },
  ],
  url: "/en-US/docs/Tools/Scratchpad",
};

const {
  title: englishTitle, // 重新命名
  translations: [
    {
      title: localeTitle, // 重新命名
    },
  ],
} = metadata;

console.log(englishTitle);   // Scratchpad
console.log(localeTitle);    // JavaScript-Umgebung

陣列和物件解構也能混在同一個樣式裡。下面取出陣列第三個元素的 name 屬性:

const props = [
  { id: 1, name: "Fizz" },
  { id: 2, name: "Buzz" },
  { id: 3, name: "FizzBuzz" },
];

const [, , { name }] = props;

console.log(name);   // FizzBuzz

在迴圈中也可以直接解構每一筆資料。依 MDN 說明,for...in、for...of 的迴圈變數、函式參數與 catch 的綁定變數,都能使用宣告樣式的解構:

const people = [
  { name: "Mike Smith", family: { father: "Harry Smith" }, age: 35 },
  { name: "Tom Jones", family: { father: "Richard Jones" }, age: 25 },
];

for (const {
  name: n,
  family: { father: f },
} of people) {
  console.log(`Name: ${n}, Father: ${f}`);
}
// Name: Mike Smith, Father: Harry Smith
// Name: Tom Jones, Father: Richard Jones

剩餘(rest)寫法

解構樣式的最後可以加 ...rest,把沒被取走的部分收集起來。陣列解構時,收集剩下的元素成為新陣列;物件解構時,收集沒被取走的自身可列舉屬性成為新物件:

const { a, ...others } = { a: 1, b: 2, c: 3 };
console.log(others);    // { b: 2, c: 3 }

const [first, ...others2] = [1, 2, 3];
console.log(others2);   // [ 2, 3 ]

剩餘項目必須放在樣式的最後面,後面不能有逗號:

try {
  new Function("const [a, ...b,] = [1, 2, 3];");
} catch (e) {
  console.log(e.name);   // SyntaxError
}

和其他 JavaScript 功能一樣,這裡沒有隱含的深拷貝。剩餘項目會建立新的物件或陣列,但裡面的成員如果是物件,仍然是同一個參照。

剩餘寫法的 ... 和展開語法(spread syntax)長得一樣,但方向相反:展開是把陣列攤開,剩餘是把多個值收集起來。展開語法的細節請參考展開語法的語法文。

函式參數解構

函式的參數也可以直接解構,在函式內使用取出的變數。下面的使用者物件用來示範三種寫法:

const user = {
  id: 42,
  displayName: "jdoe",
  fullName: {
    firstName: "Jane",
    lastName: "Doe",
  },
};

function userId({ id }) {
  return id;
}

function userDisplayName({ displayName: dname }) {
  return dname;
}

function whois({ displayName, fullName: { firstName: name } }) {
  return `${displayName} is ${name}`;
}

console.log(userId(user));            // 42
console.log(userDisplayName(user));   // jdoe
console.log(whois(user));             // jdoe is Jane

userId 直接取出 id;userDisplayName 把 displayName 改名為 dname;whois 同時取出外層的 displayName 和巢狀的 fullName.firstName。

參數也能搭配預設值。MDN 的範例讓 size、coords、radius 各自有預設值:

function drawChart({
  size = "big",
  coords = { x: 0, y: 0 },
  radius = 25,
} = {}) {
  console.log(size, coords, radius);
}

drawChart({
  coords: { x: 18, y: 30 },
  radius: 30,
});
// big { x: 18, y: 30 } 30

drawChart();
// big { x: 0, y: 0 } 25

參數列最後的 = {} 是整個解構樣式的預設值。沒有這個預設值時,呼叫函式至少要傳一個引數,不能不帶引數直接呼叫:

function noDefault({ size = "big" }) {
  return size;
}

try {
  noDefault();
} catch (e) {
  console.log(e.name);   // TypeError
}

console.log(noDefault({}));   // big

陣列也能這樣解構,常見的是處理陣列的每一筆資料。下面的回呼函式參數直接取出子陣列的兩個元素,陣列的 map() 用法請參考 JS Array.map() 用法:轉換每個元素:

const pairs = [[1, 2], [3, 4]];

console.log(pairs.map(([a, b]) => a + b));   // [ 3, 7 ]

解析正規表達式的比對結果

RegExp.prototype.exec() 找到符合的字串時,回傳的陣列第一個元素是完整比對,之後是各個括號群組。用解構略過第一個元素,就能直接取出群組:

function parseProtocol(url) {
  const parsedURL = /^(\w+):\/\/([^/]+)\/(.*)$/.exec(url);
  if (!parsedURL) {
    return false;
  }

  const [, protocol, fullHost, fullPath] = parsedURL;
  return protocol;
}

console.log(
  parseProtocol("https://developer.mozilla.org/en-US/docs/Web/JavaScript"),
);   // https

注意事項

  1. 陣列依位置、物件依名稱對應:陣列解構的順序很重要,物件解構的順序不影響結果。
  2. 重新命名時冒號左邊是屬性、右邊是變數:{ p: foo } 之後只有 foo 可以使用。
  3. 預設值只在 undefined 時使用:值是 null、0、空字串時,不會使用預設值。
  4. 不能解構 null 與 undefined:會丟出 TypeError,需要時先確認值存在,或在函式參數加 = {} 之類的預設值。
  5. 沒有宣告關鍵字的物件解構要加小括號:({ a, b } = obj);。
  6. 剩餘項目要放最後:後面不能再有其他項目或逗號。
  7. 解構是淺層的:取出的物件成員仍是同一個參照,沒有深拷貝。
  8. 陣列解構需要可迭代的值:一般物件要改用物件解構。

支援版本

依 MDN 瀏覽器相容性資料(browser-compat-data 8.1.10,查詢日期 2026-11-24):

環境基本解構陣列的 rest物件的 rest
Chrome494960
Edge141679
Firefox414155
Safari89.111.1
Node.js6.0.06.0.08.3.0

Deno 從 1.0 開始支援,Internet Explorer 不支援。MDN 另外註明,Firefox 2 到 40 提供過非標準的解構實作。

補充說明:範例在 Node.js v22.20.0 執行。多數範例來自 MDN 的 Destructuring 頁面;map() 回呼函式的解構是依 MDN 所說「函式參數可用解構樣式」另外撰寫的示範。

參考資料與延伸閱讀

發佈留言