简体   繁体   English

深度数组上的JavaScript深度传播运算符

[英]JavaScript deep spread operator on deep arrays

I have a deep array, hence the array with arrays children like below: 我有一个很深的数组,因此带有子数组的数组如下所示:

const deepArray = ['1',[['a'],['b']],[2],[[[['4',[3,'c']]]],[5]]];

I wanna set all end children in a flat array, I use spread operator of ES6 but it spread shallow, I have no idea to how to make them to below: 我想将所有最终子级设置为一个平面数组,我使用ES6 spread operator ,但它散布得很浅,我不知道如何将它们设置为以下形式:

const shallowArray = ['1','a','b',2,'4',3,'c',5];

Maybe a recursive function can do it but how? 也许递归函数可以做到,但是怎么办呢? it should be very optimized because I wanna use it in a react native project. 它应该非常优化,因为我想在react native项目中使用它。 I'm worried about crash so I'm very cautious about optimization. 我担心崩溃,因此我对优化非常谨慎。

Use Array.prototype.flat to flatten the array, then use the spread operator as needed. 使用Array.prototype.flat展平阵列,然后根据需要使用散布运算符。

If you know the arrays depth or max size of depth, use the following code: 如果您知道数组的深度或最大深度值,请使用以下代码:

const flatArray = deepArray.flat(7); // assume you know depth size is 7

If you don't know the depth, you can use a recursive method that using reduce function, use below: 如果您不知道深度,则可以使用使用reduce函数的递归方法,请使用以下方法:

 const deepFlatten = arr =>
         arr.reduce(
           (acc, val) =>
             Array.isArray(val) 
               ? acc.concat(deepFlatten(val)) 
               : acc.concat(val),
             []
         );

Use above function to flat undeterminate depth: 使用以上功能可以平整不确定的深度:

const flatArray = deepFlatten(deepArray);

Using recursion, its pretty straightforward :) 使用递归,它非常简单:)

 let deepArray = ['1',[['a'],['b']],[2],[[[['4',[3,'c']]]],[5]]]; let array = []; function f(d){ Array.isArray(d)? d.forEach(x=> f(x)) : array.push(d); } deepArray.forEach(x=>f(x)); console.log(array); 

I want a flatten function for react-native merge styles. 我想要一个用于react-native合并样式的扁平函数。 because in react-native sometimes you have a deep array of styles and it is essential to flat them. 因为有时在react-native您会有各种各样的样式,因此必须扁平化样式。

But I find out the react-native StyleSheet have a good and optimized flatten function for handling this problem. 但是我发现react-native StyleSheet具有良好的优化flatten函数,可以处理此问题。

If someone read my question and need to handle deep arrays of style use below code: 如果有人阅读了我的问题,并且需要处理深层样式,请使用以下代码:

const styleJoiner = (...arg) => StyleSheet.flatten(arg);

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

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