##作用:
清除数组中的非真值
const arr = [1,2,3],brr = [4], crr = 5,err = [[6]];
const drr = _.concat(arr,brr,crr,err);
console.log(drr) // [1,2,3,4,5,[6]]
##源码:
function concat() {
var length = arguments.length;
if (!length) {
return [];
}
//这里把 arguments 分为了两个值 第一个值 array:any 和剩下的值组成的数组
var args = Array(length - 1),
array = arguments[0],
index = length;
//这里是4
while (index--) {
//注意args的长度比 arguments 小一位
//所以这里需要一个减一 原本位于 arguments 下标为1的值,在args中下标为0
args[index - 1] = arguments[index];
}
return arrayPush(
//这里判断第一个值是不是数组对象,如果不是把他变为数组的第一个元素
isArray(array) ? copyArray(array) : [array],
//一级拉平的关键代码.我在这里面页迷糊了
baseFlatten(args, 1));
}
//这是一个浅克隆的数组的代码
function copyArray(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
function baseFlatten(array, depth, predicate, isStrict, result) {
var index = -1,
length = array.length;
//predicate 默认为判断是否为数组,或者类数组对象 如: arguments
predicate || (predicate = isFlattenable);
result || (result = []);
while (++index < length) {
var value = array[index];
if (depth > 0 && predicate(value)) {
if (depth > 1) {
// Recursively flatten arrays (susceptible to call stack limits).
baseFlatten(value, depth - 1, predicate, isStrict, result);
} else {
//如果你在concat参数中有数组在这里(第一个参数不走这里)
arrayPush(result, value);
}
} else if (!isStrict) {
result[result.length] = value;
}
}
return result;
}
// 把 values的值添加在array数组的后面,多次用到这个函数
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
//注意这里判断的使用values的length属性
while (++index < length) {
//注意在array 后面直接做push操作
array[offset + index] = values[index];
}
return array;
}
##总结:
主要看作者的编程思想和实现逻辑