展平锯齿状的多维数组 [英] Flatten a jagged multi dimensional array
本文介绍了展平锯齿状的多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要帮助扁平化这样的数组:
I need help flattening an array like this:
[1,2,[2,3],[5,[6,1],4],7]
我希望它像
[1,2,2,3,5,6,1,4,7].
我搜索过类似的东西,找到了[].concat.apply
,但它只会处理二维数组.
I have searched something like this, and found [].concat.apply
, but it will only take care of the two dimensional arrays.
我还想使用一种适用于任何锯齿状多维数组的算法.请帮忙.谢谢
I also want to use an algorithm that will work for any jagged multi dimensional arrays. Please help. Thx
推荐答案
您可以将 concat.apply
内容包装在循环中以处理深度嵌套的数组:
You can wrap the concat.apply
thing in a loop to handle deeply nested arrays:
while (a.some(Array.isArray))
a = [].concat.apply([], a)
或在 ES6 语法中:
or in the ES6 syntax:
while (a.some(Array.isArray))
a = [].concat(...a);
这篇关于展平锯齿状的多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文