function baseFlatten(array, depth, predicate, isStrict, result)
_.flatten 的基本实现,支持限制展平。
@param {Array} array The array to flatten.
要展平的数组。
@param {number} depth The maximum recursion depth.
最大递归深度。
@param {boolean} [predicate=isFlattenable] The function invoked per iteration.
每次迭代调用的函数。
@param {boolean} [isStrict] Restrict to values that pass
predicatechecks.
限制为通过predicate检查的值。
@param {Array} [result=[]] The initial result value.
初始结果值。
function baseFlatten(array, depth, predicate, isStrict, result) {
// 下标
var index = -1,
// 数组长度
length = array.length;
// 若第三个参数不存在,则赋值为 isFlattenable 方法
predicate || (predicate = isFlattenable);
// 若 result 默认为 空数组
result || (result = []);
// 循环
while (++index < length) {
// 提取当前元素
var value = array[index];
// 判断展平层数(需要被展平)
// 并且当前元素是可以展平的数组或伪数组
if (depth > 0 && predicate(value)) {
// 若展平次数大于1,则产生函数回调,展平数组
if (depth > 1) {
// Recursively flatten arrays (susceptible to call stack limits).
// 这一步将 result 和 value 一同传了进去,所以在函数回调中也修改了 result 的内容
// depth - 1 减少展平层级,比如一开始传入2表示展平2层,那么回调时应该只是展平1层
baseFlatten(value, depth - 1, predicate, isStrict, result);
} else {
// 否则将此 value 添加进结果数组中
arrayPush(result, value);
}
} else if (!isStrict) {
// 否则添加内容到 result 中
result[result.length] = value;
}
}
return result;
}












网友评论