lodash 源码解读 _.flattenDepth(array, num)

Posted bbb324

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lodash 源码解读 _.flattenDepth(array, num)相关的知识,希望对你有一定的参考价值。

_.flattenDepth(arr, depth) 按指定层级展开数组

var array = [1, [2, [3, [4]], 5]];
 
  _.flattenDepth(array, 1);
  // => [1, 2, [3, [4]], 5]
   
  _.flattenDepth(array, 2);
  // => [1, 2, 3, [4], 5]
  function flattenDepth(array, depth) {
      var length = array == null ? 0 : array.length;
      if (!length) {
        return [];
      }
      depth = depth === undefined ? 1 : toInteger(depth);
      return baseFlatten(array, depth);
  }
  function baseFlatten(array, depth, predicate, isStrict, result) {
      var index = -1,
          length = array.length;

      predicate || (predicate = isFlattenable);
      result || (result = []);

      while (++index < length) {
        var value = array[index];
        if (depth > 0 && predicate(value)) {
          if (depth > 1) { //通过递归的形式来扩展数组        
            baseFlatten(value, depth - 1, predicate, isStrict, result);
          } else {
            arrayPush(result, value);//将结果 value 添加到数组 result
          }
        } else if (!isStrict) {
          result[result.length] = value;
        }
      }
      return result;
    }

 

以上是关于lodash 源码解读 _.flattenDepth(array, num)的主要内容,如果未能解决你的问题,请参考以下文章

lodash 源码解读 _chunk(array, size)

lodash 源码解读 _.findIndex(obj_array, fn)

惰性求值——lodash源码解读

RedissonDelayedQueue源码解读

HyperLedgerFabric源码解读(5)-channel

Faster RCNN源码解读(1)-NMS非极大值抑制