array-flatten使用方法和源码

2019-08-28 08:32:55

将嵌套数组的数组展开为一个平面数组。 可指定深度。

作用#

Copy    var flatten = require('array-flatten')
    
    flatten([1, [2, [3, [4, [5], 6], 7], 8], 9])    //=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    flatten([1, [2, [3, [4, [5], 6], 7], 8], 9], 2)    //=> [1, 2, 3, [4, [5], 6], 7, 8, 9]
    
    (function () {
      flatten(arguments) //=> [1, 2, 3]
    })(1, [2, 3])

Github#

https://github.com/blakeembrey/array-flatten

源码#

Copy    // 指定深度展开
    function flattenWithDepth (array, result, depth) {      for (var i = 0; i < array.length; i++) {        var value = array[i]        
        // 判断是否到了指定的深度 或者 当前数组是否已经全部展开
        if (depth > 0 && Array.isArray(value)) {
          flattenWithDepth(value, result, depth - 1)
        } else {
          result.push(value)
        }
      }    
      return result
    }    
    // 全部展开
    function flattenForever (array, result) {      for (var i = 0; i < array.length; i++) {        var value = array[i]    
        if (Array.isArray(value)) {
          flattenForever(value, result)
        } else {
          result.push(value)
        }
      }    
      return result
    }    
    function arrayFlatten (array, depth) {      if (depth == null) {        return flattenForever(array, [])
      }    
      return flattenWithDepth(array, [], depth)
    }


  • 2018-01-08 22:12:20

    加快gradle的编译速度总结-亲身经历

    这两题集成mob的maven,这个编译速度是慢的可怜啊,经过百度得出了这样一个方案,配置好以后那可是神速啊,妈妈再也不用担心我的编译速度看。嗷嗷的。

  • 2018-01-11 09:07:01

    微信小程序的组件用法与传统HTML5标签的区别

    小程序刚开放公测,互联网圈内开始了各种解读和猜测。其中有观点认为小程序和HTML5有着紧密关联,甚至小程序就是基于HTML5开发。 经过仔细研究文档和代码开发,从视图层的角度来说,小程序与传统HTML5还是有明显的区别,主要区别在于: