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


  • 2019-04-30 11:23:36

    elasticsearch和analysis-ik的安装使用

    全文搜索和中文分词主要介绍了两组全文搜索加中文分词方案; TNTSearch+jieba-php这套组合对于博客这类的小项目基本够用了;

  • 2019-04-30 11:42:24

    php7+laravel+coreseek(sphinx)中文搜索初步实现(Linux)

    官网www.coreseek.cn已不能下载,所以需从网上找资源, 注意的一点是,笔者安装coreseek-3.2.14版本后,使用时提示client版本高于server版本的错误, php的sphinx扩展,为使用者,为client;coreseek是系统服务,为server

  • 2019-04-30 13:55:13

    浅谈mysql fulltext全文索引优缺点

    为什么会注意到mysql的fulltext? nima, 还是上次innodb转成tokudb引擎的事,这次alter修改表引擎的时候,提示percona tokudb是不支持fulltext索引的.

  • 2019-04-30 18:56:52

    elasticsearch文档操作

    使用了Elasticsearch提供的一整套强大的REST API,本文继续来看通过这一套API如何完成文档的基本操作。

  • 2019-05-05 14:04:11

    PHP使用CURL模拟POST/GET/PUT/DELETE方式提交数据

    最近因为工作需要,调用网盘接口来上传文件,我用了CURL库, 当然在用CURL库之前必须要在php中启用 cURL 设置 可以通过使用php_info()函数来得到cURL信息,如果看不到cURL信息的话,那么需要设置PHP并开启这个库。在Windows平台下,需要改一改php.ini文件的设置,找到 php_curl.dll,并取消前面的分号注释就行了。