image.png
    1、使用flat() es6
    语法 Array.flat(depth);
    depth表示深度 默认1, 使用Infinity可展开任意深度嵌套的数组
    2、使用yield* es6 https://www.yuque.com/zhangwujian/js/uk6fcx

    1. function* iterTree(tree){
    2. if(Array.isArray(tree)){
    3. for(let i = 0 ;i<tree.length;i++){
    4. yield* iterTree(tree[i]);
    5. }
    6. }else{
    7. yield tree;
    8. }
    9. }
    10. let arr1 = [1, 2, ['a', 'b', ['中', '文', [1, 2, 3, [11, 21, 31]]]], 3];
    11. for (const x of iterTree(arr1)) {
    12. console.log(x);
    13. }

    3、使用while + Array.some() + Array.isArray() + concat + … 展开运算符

    1. function iterTree2(arr) {
    2. while (arr.some(item => Array.isArray(item))) {
    3. arr = [].concat(...arr);
    4. }
    5. return arr;
    6. }
    7. console.log(iterTree2(arr1));

    4、数组的reduce属性
    5、使用while + shift + unshift。循环 shift一个数组成员判断是否是数组,是则unshift加入到数组开头,然后继续shift第一个成员,否则push进目标数组。不用递归

    1. var arr1 = [1, 2, [3], [1, 2, 3, [4, [2, 3, 4]]]];
    2. function flatten(input) {
    3. const stack = [...input]; //保证不会破坏原数组
    4. const result = [];
    5. while(stack.length) {
    6. const first = stack.shift();
    7. if(Array.isArray(first)) {
    8. stack.unshift(...first);
    9. } else{
    10. result.push(first);
    11. }
    12. }
    13. return result;
    14. }
    15. flatten(arr1); //[1, 2, 3, 1, 2, 3, 4, 2, 3, 4]

    6、如果是纯数字可以使用toString 然后split最后map转换数据类型。详见知乎链接

    https://www.cnblogs.com/yinping/p/11232361.html

    https://zhuanlan.zhihu.com/p/121731551