J

JavaScript 数组.flatMap()

2025-06-10

JavaScript 数组.flatMap()

SamanthaMing.com 的 CodeTidbit

在我之前的花​​絮中,你学习了Array.flat()map()如何展平数组。现在让我们来换个角度,介绍一下“flatMap”。它结合了先用& 映射数组,然后再调用 的步骤flat()。与其调用 2 个方法,不如直接使用flatMap()👍

const foods = ['🍫', '🍦' ]


// ❌ map + flat
foods.map(food => [food, '😋']).flat()


// ✅ flatMap
foods.flatMap(food => [food, '😋'])


// Result
// ['🍫', '😋', '🍦', '😋']
Enter fullscreen mode Exit fullscreen mode

怎么flatMap()運作?

让我们一步一步地看看它flatMap()是怎么做的。我第一次学习这个的时候有点困惑。因为我以为它会先展平,然后再进行映射。但不是🙅。它先……map()然后flat()……

const names = ['jane', 'john' ];

// Step 1: map
const nestedArray = names.map((name, index) => [name, index]);
// [ ['jane', 1], ['john', 2 ] ]
Enter fullscreen mode Exit fullscreen mode

现在我们有了一个嵌套数组。我们可以用它flat()来展平这个数组。

const nestedArray =  [ ['jane', 1], ['john', 2 ] ]

nestedArray.flat();
// [ 'jane', 1, 'john', 2 ]
Enter fullscreen mode Exit fullscreen mode

当然,我们可以简化它,直接调用flatMap()。我们来看看 👀

const names = ['jane', 'john' ];

const result = names.flatMap((name, index) => [name, index]);

// [ 'jane', 1, 'john', 2 ]
Enter fullscreen mode Exit fullscreen mode

瞧!结果一样了👍

flatMap仅展平 1 层深度

使用flat(),它接受一个参数来设置深度。这意味着你可以指定嵌套数组的展平深度。

const depth1 = [ [1], [2] ];
depth1.flat(); // same as depth.flat(1)
// [1, 2]

const depth2 = [ [[1, 2]] ];
depth2.flat(2);
// [1, 2]
Enter fullscreen mode Exit fullscreen mode

现在对于flatMap(),您只能深入 1 级。

const names = ['jane'];

names.flatMap((name, index) => [ [name, index] ]);
//  [ ['jane', 1] ]
Enter fullscreen mode Exit fullscreen mode

让我们将其分为两个步骤,以便您了解发生了什么。

const names = ['jane'];

// Step 1: created a 2-level deep array
const twoLevelDeep = names.map((name, index) => [ [name, index] ]);
// [ [ ['jane', 1] ] ]

// Step 2: flat using depth 1
twoLevelDeep.flat();
//  [ ['jane', 1] ]
Enter fullscreen mode Exit fullscreen mode

但如果你单独执行此操作,我可以传递一个depth参数并将其完全展平:

twoLevelDeep.flat(2);
// [ 'jane', 0, 'john', 1 ]
Enter fullscreen mode Exit fullscreen mode

因此,如果您希望它的深度超过 1,那么最好不要使用flatMap(),而只是分别调用方法👍

flatMap过滤项目

一个非常酷的功能flatMap是删除一个元素。在这个例子中,我想删除所有负数。

const numbers = [1, 2, -3, -4, 5];

numbers.flatMap(number => {
  return number < 0 ? [] : [number]
})

// [ 1, 2, 5]
Enter fullscreen mode Exit fullscreen mode

这真是太酷了!就像在表演一个filter。但这实际上是怎么运作的呢?秘密就在于空数组。让我们看看我的意思。

const emptyNestedArray = [ [], 1 ];

emptyNestedArray.flat();
// [ 1 ]
Enter fullscreen mode Exit fullscreen mode

当你尝试展平一个空数组元素时,它只会删除该元素。所以我们可以利用这一点,让flatMapact 看起来像一个filter方法。是不是很棒!👍

资源


感谢阅读❤
打个招呼!Instagram | Twitter | Facebook |博客| SamanthaMing.com

鏂囩珷鏉ユ簮锛�https://dev.to/samanthaming/javascript-array-flatmap-3h4g
PREV
使用 || 和 console.log GenAI LIVE! 快速调试 | 2025 年 6 月 4 日
NEXT
如何获取对象的长度