filter 过滤器 和 zip 合并数组
filter
一个简单的过滤器, 因为 for of ,使得其可以适用于数组和对象
_.filter = (array,fn)=>{
let results = [];
for(const value of array){
(fn(value)) ? results.push(value) : undefined;
}
return results;
}
zip
按照相应传入的fn规则合并对应数组
_.zip = (leftArr,rightArr,fn)=>{
let index,len,result = [];
let [leftArrLen,rightArrLen] = [leftArr.length,rightArr.length];
for(index = 0,len = Math.min(leftArrLen,rightArrLen);index<len;index++){
result.push(fn(leftArr[index],rightArr[index]));
}
//如果两个数组长度不同,直接在result后面加上多出部分数组
if(leftArrLen > rightArrLen){
result = result.concat(leftArr.slice(rightArrLen,leftArrLen));
}else if(leftArrLen < rightArrLen){
result = result.concat(rightArr.slice(leftArrLen,rightArrLen));
}
return result;
}
示例:
let a = [1,2,3,4];
let b = [2,1,2];
console.log(_.zip(a,b,(l,r)=>l+r)); // [ 3, 3, 5, 4 ]
Last updated
Was this helpful?