對于前端項目開發(fā)過程中,偶爾會出現(xiàn)層疊數據結構的數組,我們需要將多層級數組轉化為一級數組(即提取嵌套數組元素最終合并為一個數組),使其內容合并且展開。那么該如何去實現(xiàn)呢?

image.png
需求:多維數組=>一維數組
const numbers = [1, 2, [3, 4, [5, 6]]];
// Considers default depth of 1
numbers.flat();
> [1, 2, 3, 4, [5, 6]]
// With depth of 2
numbers.flat(2);
> [1, 2, 3, 4, 5, 6]
// Executes two flat operations
numbers.flat().flat();
> [1, 2, 3, 4, 5, 6]
// Flattens recursively until the array contains no nested arrays
numbers.flat(Infinity)
> [1, 2, 3, 4, 5, 6]
參考地址:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/flat