本文共 2718 字,大约阅读时间需要 9 分钟。
introduced two new methods to the Array prototype: flat
and flatMap
. They are both very useful to what we want to do: flatten an array.
为Array原型引入了两种新方法: flat
和flatMap
。 它们对我们想要做的事情都非常有用: 展平array 。
Let’s see how they work.
让我们看看它们是如何工作的。
But first, a word of warning: only Firefox 62+, Chrome 69+, Edge 76+ and Safari 12+ do already support those 2 methods, as they are fairly recent. Check the , and remember you can use to backport your code to a previous ES version, if you need to support older browsers.
但首先,要提个警告:只有Firefox 62 +,Chrome 69 +,Edge 76+和Safari 12+已经支持这两种方法,因为它们是相当新的。 检查 ,并记住,如果需要支持较旧的浏览器,可以使用将代码反向移植到以前的ES版本。
If you don’t want to deal with Babel, and you don’t have a build step already, it might make more sense to use the , and functions provided by Lodash.
如果您不想使用Babel,并且还没有构建步骤,那么使用提供的 , 和函数可能更有意义。
The cool thing about Lodash is that you don’t need to import the whole library. You can use those functions individually using those packages:
Lodash的妙处在于您无需导入整个库。 您可以使用以下软件包单独使用这些功能:
Here’s how to flatten an array using lodash.flatten
:
这是使用lodash.flatten
展平数组的方法:
const flatten = require('lodash.flatten')const animals = ['Dog', ['Sheep', 'Wolf']]flatten(animals)//['Dog', 'Sheep', 'Wolf']
Let’s now talk about the native flat()
and flatMap()
JavaScript methods now.
现在让我们现在讨论原生的flat()
和flatMap()
JavaScript方法。
flat()
is a new array instance method that can create a one-dimensional array from a multidimensional array.
flat()
是一种新的数组实例方法,可以从多维数组创建一维数组。
Example:
例:
['Dog', ['Sheep', 'Wolf']].flat()//[ 'Dog', 'Sheep', 'Wolf' ]
By default it only “flats” up to one level.
默认情况下,它仅“展平”到一个级别。
You can add a parameter to flat()
to set the number of levels you want to flat the array to.
您可以向flat()
添加参数以设置要将数组平面化的级别数。
Set it to Infinity
to have unlimited levels:
将其设置为Infinity
以具有无限级别:
['Dog', ['Sheep', ['Wolf']]].flat()//[ 'Dog', 'Sheep', [ 'Wolf' ] ]['Dog', ['Sheep', ['Wolf']]].flat(2)//[ 'Dog', 'Sheep', 'Wolf' ]['Dog', ['Sheep', ['Wolf']]].flat(Infinity)//[ 'Dog', 'Sheep', 'Wolf' ]
If you are familiar with the JavaScript map()
method of an array, you know that using it you can execute a function on every element of an array.
如果您熟悉数组JavaScript map()
方法,那么您就会知道,使用它可以对数组的每个元素执行一个函数。
If not, check my .
如果没有,请查看我的 。
flatMap()
is a new Array prototype method that combines flat()
with map()
. It’s useful when calling a function that returns an array in the map()
callback, but you want your resulted array to be flat:
flatMap()
是一个新的Array原型方法,将flat()
与map()
结合在一起。 在调用返回map()
回调中的数组的函数时非常有用,但是您希望得到的数组是平坦的:
['My dog', 'is awesome'].map(words => words.split(' '))//[ [ 'My', 'dog' ], [ 'is', 'awesome' ] ]['My dog', 'is awesome'].flatMap(words => words.split(' '))//[ 'My', 'dog', 'is', 'awesome' ]
翻译自:
转载地址:http://pxqgb.baihongyu.com/