简体   繁体   English

如何在JavaScript中展平数组?

[英]How to flattening array at javascript?

I have code [ 1, 2, 3, fn(), 7, 8 ] 我有代码[ 1, 2, 3, fn(), 7, 8 ]

The fn does next: fn接下来fn是:

fn(){ return [ 5, 6 ] }

Which operator to apply to fn() call to get: 将哪个运算符应用于fn()调用以获取:

[ 1, 2, 3, 5, 6, 7, 8 ]

instead of: 代替:

[ 1, 2, 3, [ 5, 6 ], 7, 8 ]

Of course It is possible to do: 当然可以:

[ 1, 2, 3, fn(), 7, 8 ].flat()

But at this case other elements will be flattened too. 但是在这种情况下,其他元素也将被展平。 I need flattening only for fn() 需要为fn()

When calling fn , spread it into the array you're creating: 调用fn传播到您要创建的数组中:

 const fn = () => [ 5, 6 ]; const arr = [ 1, 2, 3, ...fn(), 7, 8, [9, 10]] console.log(arr); 

flatMap() returns values of the callback function of each element of the input array as an array which is then returned flattened. flatMap()以数组形式返回输入数组每个元素的回调函数的值,然后将其展平。 For example, the callback can be made to return the following: 例如,可以使回调返回以下内容:

  • One-to-one: return [ value ] 一对一:返回[ value ]
  • One-to-none: return [ ] 一对一:返回[]
  • One-to-many: return [ value , value -5, arbritaryValue ] 一对多: return [ valuevalue -5, arbritaryValue ]

In the demo if the value is an array -- it will be returned as is -- otherwise it will be returned within an array. 在演示中,如果值是数组-它将按原样返回-否则它将在数组内返回。 Essentially, all values will be returned from callback as an array which in turn gets flattened. 本质上,所有值都将从回调作为数组返回,而数组又将被展平。

 const fn = () => [5, 6]; let array = [1, 2, 3, 4, fn(), 7, 8]; const result = array.flatMap(node => Array.isArray(node) ? node : [node]); console.log(result); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM