码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-06-02 17:19:34      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:源码解读   扩展   class   ret   var   blog   dex   cti   null   

_.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)

标签:源码解读   扩展   class   ret   var   blog   dex   cti   null   

原文地址:http://www.cnblogs.com/bbb324/p/6933699.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!