zoukankan      html  css  js  c++  java
  • 多维数组 转化为 一维数组

    初级 : 将二维数组 变成 一维数组
     
     
    方式一 : 使用 js api
     
    (function(){
        let origin = [1,2,[3,4],5];
        let convert = origin.flat();
        console.log(convert); // display [1,2,3,4,5]
    })();
     
     
    方式二 : 使用 reduce + concat, 进行一级深度的扁平化处理
     
    (function(){
        let origin = [1,2,3,[4,5]];
        
        function flat_with_reduce(arr){
            return arr.reduce((sum,current) => sum.concat(current),[])
        }
        
        let result = flat_with_reduce(origin);
        console.log(result);
    })();
     
    方式三 : 使用 ... + concat 进行一级深度的扁平化处理
    (function(origin){
        let result = [].concat(...origin)
        console.log(result);
    })([1,2,3,[4,5]]);
    进阶 : 将多维数组 转化为 一维数组
     
    方式① : 使用 reduce + concat + 递归
    (function(origin){
        function flat_deep_with_reduce(arr){
            return arr.reduce( (sum,current) => Array.isArray(current) ? sum.concat(flat_deep_with_reduce(current) ) :  sum.concat(current) , [] );
        }
        
        let result = flat_deep_with_reduce(origin);
        console.log(result);
    })([1,2,[3,4,[5,6],7],8]);
     
     
    方式② : 不使用递归 , 使用堆栈
    (function(origin){
        let stack = [...origin] ;
        let converted = [];
     
        while(stack.length){
            let item = stack.pop();    //从堆栈底部 弹出元素
            if(Array.isArray(item)){
                 // 如果是数组 就扔回堆栈底部
                 // 注意扔回底部的不再是 item这个数组了
                 // 使用了 ... 之后 , 扔回去的就是一个 比 item少一维的数组 或者元素了
                stack.push(...item)
            }else{
                // 直到上面某个元素不是数组,将它 推给 converted 顶部
                converted.unshift(item)
            }
        }
        console.log(converted);
    })([1,2,[3,4,[5,6],7],8]);

    Polyfill

      flat 函数 , 在 IE 及 Edge版本中 得不到支持
      如果想实现 flat 函数的功能 , 只需要在原型中 加入上述满足需要的函数即可 .
     
    注 : 本文 来自于 MDN , javascript 分类中 flat() , 有需要的朋友可以参阅原文.
  • 相关阅读:
    Oracle 网络
    Oracle 实例管理
    Oracle 体系结构四 逻辑和物理存储结构之间的关系
    Oracle 体系结构三 后台进程
    Oracle 体系结构二 内存结构
    Oracle 体系结构一 概述
    SQL 二
    SQL 一
    如何获取SQL Server数据库元数据的方法
    VB.NET中使用代表对方法异步调用
  • 原文地址:https://www.cnblogs.com/lmxxlm-123/p/11131545.html
Copyright © 2011-2022 走看看