Movatterモバイル変換


[0]ホーム

URL:


  1. 給開發者的 Web 技術文件
  2. JavaScript
  3. JavaScript 參考文件
  4. 標準內建物件
  5. Array
  6. Array.prototype.flat()

此頁面由社群從英文翻譯而來。了解更多並加入 MDN Web Docs 社群。

View in EnglishAlways switch to English

Array.prototype.flat()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2020年1月⁩.

實驗性質:這是一個實驗中的功能
此功能在某些瀏覽器尚在開發中,請參考兼容表格以得到不同瀏覽器用的前輟。

flat() 函數以遞迴方式將特定深度的子陣列重新串接成為一新的陣列

嘗試一下

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
var newArray = arr.flat([depth]);

參數

depth選擇性

指定巢狀陣列展開的深度。預設為 1。

回傳值

函數將會回傳一個由原先陣列的子陣列串接而成的新陣列。

範例

展開巢狀陣列

js
var arr1 = [1, 2, [3, 4]];arr1.flat();// [1, 2, 3, 4]var arr2 = [1, 2, [3, 4, [5, 6]]];arr2.flat();// [1, 2, 3, 4, [5, 6]]var arr3 = [1, 2, [3, 4, [5, 6]]];arr3.flat(2);// [1, 2, 3, 4, 5, 6]

當遭遇空元素時

flat() 函數會自動清除陣列中空的元素

js
var arr4 = [1, 2, , 4, 5];arr4.flat();// [1, 2, 4, 5]

替代方案

reduceconcat

js
var arr1 = [1, 2, [3, 4]];arr1.flat();//展開單層陣列arr1.reduce((acc, val) => acc.concat(val), []); // [1, 2, 3, 4]
js
//欲展開更深層的巢狀結構請使用reduce與concat的遞迴function flattenDeep(arr1) {  return arr1.reduce(    (acc, val) =>      Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val),    [],  );}flattenDeep(arr1); // [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
js
//使用stack來實作非遞迴的展開var arr1 = [1, 2, 3, [1, 2, 3, 4, [2, 3, 4]]];function flatten(input) {  const stack = [...input];  const res = [];  while (stack.length) {    // pop value from stack    const next = stack.pop();    if (Array.isArray(next)) {      // push back array items, won't modify the original input      stack.push(...next);    } else {      res.push(next);    }  }  //reverse to restore input order  return res.reverse();}flatten(arr1); // [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
js
// 递归版本的反嵌套function flatten(array) {  var flattend = [];  (function flat(array) {    array.forEach(function (el) {      if (Array.isArray(el)) flat(el);      else flattend.push(el);    });  })(array);  return flattend;}

規範

Specification
ECMAScript® 2026 Language Specification
# sec-array.prototype.flat

瀏覽器相容性

參見

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp