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)
    }


  • 2020-12-08 17:13:57

    nvm卸载、安装node和npm

    1、node.js、nvm、 npm (1)在cmd中输入`where node`找到node长须所在位置进行删除 (2)确保计算机-环境变量删除相关引用 (3)在cmd中输入`node -v` ,得到以下结果,删除成功

  • 2020-12-08 17:23:36

    Window下完全卸载删除Nodejs

    1.从卸载程序卸载程序和功能。 2.重新启动(或者您可能会从任务管理器中杀死所有与节点相关的进程)。 3.寻找这些文件夹并删除它们(及其内容)(如果还有)。根据您安装的版本,UAC设置和CPU架构,这些可能或可能不存在:

  • 2020-12-09 08:48:45

    nodejs版本以及其对应的npm版本

    正在寻找某个大版本的最新版? Node.js 10.x Node.js 8.x Node.js 6.x Node.js 4.x Node.js 0.12.x Node.js 0.10.x 所有版本

  • 2020-12-12 17:27:54

    手把手教你 GitLab 的安装及使用

    GitLab:是一个基于Git实现的在线代码仓库托管软件,你可以用gitlab自己搭建一个类似于Github一样的系统,一般用于在企业、学校等内部网络搭建git私服。