_.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; }
时间: 2024-10-08 00:48:35