Array.prototype.flat()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2020 年 1 月⁩ 起,所有主流瀏覽器均已支援。

flat() 方法會 Array 例項建立一個新陣列,其中所有子陣列的元素已遞迴地連線到其中,直到指定的深度。

試一試

const arr1 = [0, 1, 2, [3, 4]];

console.log(arr1.flat());
// expected output: Array [0, 1, 2, 3, 4]

const arr2 = [0, 1, [2, [3, [4, 5]]]];

console.log(arr2.flat());
// expected output: Array [0, 1, 2, Array [3, Array [4, 5]]]

console.log(arr2.flat(2));
// expected output: Array [0, 1, 2, 3, Array [4, 5]]

console.log(arr2.flat(Infinity));
// expected output: Array [0, 1, 2, 3, 4, 5]

語法

js
flat()
flat(depth)

引數

depth 可選

指定應將巢狀陣列結構展平多深的深度級別。預設為 1。

返回值

一個將子陣列元素連線到其中的新陣列。

描述

flat() 方法是 複製方法。它不會更改 this,而是返回一個 淺複製,其中包含與原始陣列相同的元素。

如果正在展平的陣列是 稀疏陣列,則 flat() 方法會刪除空槽。例如,如果 depth 為 1,則會忽略根陣列和第一級巢狀陣列中的空槽,但更深層巢狀陣列中的空槽會與陣列本身一起保留。

flat() 方法是 通用的。它只期望 this 值具有 length 屬性和整數鍵屬性。但是,它的元素必須是陣列才能進行展平。

示例

展平巢狀陣列

js
const arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]

const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

const arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

在稀疏陣列上使用 flat()

flat() 方法會刪除陣列中的 空槽

js
const arr5 = [1, 2, , 4, 5];
console.log(arr5.flat()); // [1, 2, 4, 5]

const array = [1, , 3, ["a", , "c"]];
console.log(array.flat()); // [ 1, 3, "a", "c" ]

const array2 = [1, , 3, undefined, ["a", , ["d", , "e"]], null];
console.log(array2.flat()); // [ 1, 3, undefined, "a", ["d", empty, "e"], null ]
console.log(array2.flat(2)); // [ 1, 3, undefined, "a", "d", "e", null ]

在非陣列物件上呼叫 flat()

flat() 方法讀取 thislength 屬性,然後訪問鍵小於 length 的每個非負整數鍵屬性。如果元素不是陣列,則直接將其附加到結果中。如果元素是陣列,則根據 depth 引數進行展平。

js
const arrayLike = {
  length: 3,
  0: [1, 2],
  // Array-like objects aren't flattened
  1: { length: 2, 0: 3, 1: 4 },
  2: 5,
  3: 3, // ignored by flat() since length is 3
};
console.log(Array.prototype.flat.call(arrayLike));
// [ 1, 2, { '0': 3, '1': 4, length: 2 }, 5 ]

規範

規範
ECMAScript® 2026 語言規範
# sec-array.prototype.flat

瀏覽器相容性

另見