使用 flat() 和 flatMap() 在 Vanilla JavaScript 中扁平化数组

LodashUnderscore.js这样的图书馆已经为我们提供了一些工具,帮助我们在一段时间内平行数组. 由于 ECMAScript 标准的持续发展,我们现在将获得方法直接在瓦尼拉JavaScript中做到这一点,而无需外部实用功能。

正如你可能已经看到的,如果你最近一直在跟踪跨网,这些新的方法来平板数组已经引起了相当大的动荡. 现在在 #Smooshgate被称为,其核心是,Array.prototype.flatten()正在由MooTools修补,这仍然被一些网站使用,所以在某个时候,一个提示出现以命名方法的滑稽而不是滑稽,以避免打破一些网站仍然依赖于MooTools。

现在,这个小争议的尘埃已经解决了,最终的决定是将FlatMap和FlatMap作为两种方法名称,以帮助JavaScript中平行数组。

现在让我们来超越他们。

标签 标签 标签( )

正如其名称所示,在 Array 原型上可用的 flat() 方法会返回一个新的数组,该数组是一个被调用的数组的平板版本. 如果没有通过的参数,则假定 1 的深度。

这里有一个简单的例子:

1const animals = [['🐕', '🐶'], ['😺', '🐈']];
2
3const flatAnimals = animals.flat();
4// same as: const flatAnimals = animals.flat(1);
5
6console.log(flatAnimals);
7
8// ['🐕', '🐶', '😺', '🐈']

注意当数组的总深度大于平面方法的最大深度时会发生什么:

1const animals = [['🐕', '🐶'], ['😺', '🐈', ['😿',['🦁'], '😻']]];
2
3const flatAnimals = animals.flat(2);
4
5console.log(flatAnimals);
6// ['🐕', '🐶', '😺', '🐈', '😿',['🦁'], '😻']

您可以使用 Infinity 如果您想要平衡任意深度的数组:

1const animals = [['🐕', '🐶'], ['😺', '🐈', ['😿',['🦁'], '😻']]];
2
3const flatAnimals = animals.flat(Infinity);
4
5console.log(flatAnimals);
6// ['🐕', '🐶', '😺', '🐈', '😿', '🦁', '😻']

Array.prototype.flatMap( )

在 Array 原型上可用的 flatMap() 方法具有相同的效果,如使用 map() 方法,然后使用 flat() 方法,默认深度为 1。

这里有一个例子:

 1const animals = ['🐕', '🐈', '🐑', '🐮'];
 2const noises = ['woof', 'meow', 'baa', 'mooo'];
 3
 4const mappedOnly = animals.map((animal, index) => [animal, noises[index]]);
 5const mappedAndFlatten = animals.flatMap((animal, index) => [animal, noises[index]]);
 6
 7console.log(mappedOnly);
 8// [['🐕', 'woof'], ['🐈', 'meow'], ['🐑', 'baa'], ['🐮', 'mooo']
 9
10console.log(mappedAndFlatten);
11// ['🐕', 'woof', '🐈', 'meow', '🐑', 'baa', '🐮', 'mooo']

返回函数通过到 **flatMap()**预计与可以传入到传统的 map() 方法相同的参数,第一个是当前值,第二个是数组中的当前值的索引,第三个是正在绘制的整个数组。

浏览器支持

例如,这些方法在Chrome 69+,Firefox 62+和Safari 12+中得到支持。

如果您想现在开始使用它并支持所有浏览器,您可以随时使用官方的polyfill/shim用于 flatflatMap

Published At
Categories with 技术
Tagged with
comments powered by Disqus