首页 > 代码库 > lodash 源码解读 _.flattenDepth(array, num)

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 =http://www.mamicode.com/ 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)