JavaScript函数式编程-数组的函数式编程(下)
1.concatAll:
concatAll
的作用是把所有嵌套的数组,连接到一个数组中去,又可以称作降级
。
🚀 下面先来看下concatAll
的实现:
//concatAll的实现
const concatAll = (array)=>{
let result = [];
for(const value of array){
result.push.apply(result,value);
};
return result;
}
result.push.apply(result,value)
这段代码其实数组的apply
方法,数组成为了apply
方法的参数,从而实现了数组的降维。- 再就是
闭包
结合for of
的使用,返回对应的结果。
🚀 接着来看下面的例子,从appressBooks2
中获取含有title
和author
对象,且评分高于4.5
的对象。
- 先试用
map
获取book.bookDetails
组成的数组,但是book.bookDetail
本身就是数组,就生成了数组嵌套数组的数据结构了。
let apressBooks2 = [
{
name : "beginners",
bookDetails : [
{
"id": 111,
"title": "你不知道的js(上)",
"author": "ANDREW TROELSEN",
"rating": [4.7],
"reviews": [{good : 4 , excellent : 12}]
},
{
"id": 222,
"title": "你不知道的js(中)",
"author": "Rahul Khanna",
"rating": [4.5],
"reviews": []
}
]
},
{
name : "pro",
bookDetails : [
{
"id": 333,
"title": "javascript高级程序设计",
"author": "Adam Freeman",
"rating": [4.0],
"reviews": []
},
{
"id": 444,
"title": "javascript悟道",
"author": "Adam Freeman",
"rating": [4.2],
"reviews": [{good : 14 , excellent : 12}]
}
]
}
];
var concatAllResult = arrayFuncs.concatAll(arrayFuncs.map(apressBooks2,(book)=>{
return book.bookDetails
}));
console.log(concatAllResult);
- 如上图实例代码,
concatAll
接收了一个二维的数组,最后降为一维数组。
生成的一维数组结果如下图:
2.reduce:
js
中数组的reduce
方法,大家应该已经熟悉,当然也可以参照下MDN
的文档(developer.mozilla.org/zh-CN/docs/…)
笔者这里不占用更多篇幅,直接上实现的函数(这里着重在于实现,reduce
应用后续单独划分):
//reduce
const reduce = (array,fn,initVal)=>{
let accumlator;
if(initVal !== undefined){
accumlator = initVal;
}else{
accumlator = array[0];
}
if(initVal === undefined){
for(let i = 1;i<array.length;i++){
accumlator = fn(accumlator,array[i]);
}
}else{
for (const value of array){
accumlator = fn(accumlator,value);
}
}
return [accumlator]
};
fn函数
接收两个参数,一个是上次的累计值
,另一个是本次运行的新值
- 根据
reduce
函数是否有初始值initVal
,从而决定循环是从0
开始还是从1
开始
3.zip函数:
zip
函数式用来合并2个
给定的数组。实现如下:
//zip
const zip = (arr1,arr2,fn)=>{
let result = [];
for(let index= 0;index< Math.min(arr1.length,arr2.length);index++){
result.push(fn(arr1[index],arr2[index]));
}
return result;
}
- 通过
Math.min
来获取长度较小
的那个数组,并以他的长度为基准
- 通过
for
循环将结果放入result
中,然后返回。
🚀 测试:
console.log(arrayFuncs.zip([1,2,3],[4,5,6],(x,y)=>x+y));
//结果为[5,7,9]
需要注意的是在处理引用类型(数组、对象等)
的数据,需要通过克隆
,这样可以使用克隆的数据进行处理,而不影响原来的数据。
Object.assign({},"要克隆的对象")
,但是需要注意的是,此方法为浅拷贝。
转载自:https://juejin.cn/post/7064193474287501342