这是我参与2022首次更文挑战的第2天,活动详情查看:2022首次更文挑战」
1.forEach和map的简单对比:
🚀 投影:把函数应用于一个值,并创建一个新值的过程称之为投影。
🚀 forEach函数:
//forEach的实现
const forEach = (array, fn) => {
for (const value of array) {
fn(value);
}
};
let arr1 = [1, 2, 3, 4, 5, 6];
forEach(arr1, (a) => {
return a + 1;
});
console.log(arr1);
🚀 map函数:
//map函数的实现
let arr1 = [1, 2, 3, 4, 5, 6];
const map = (array,fn)=>{
let result = [];
for(const value of array){
result.push(fn(value))
}
return result;
};
console.log(map(arr1,(a)=>{
return a*a;
}));
结果如上图,这里做一个简单的对比,forEach是不改变原数组的,map会生成新数组
2.封装数组的工具类:
因为这里后续还有一些数组的方法,为了使用以及维护的方便,这里将其封装到对象中,以后自己封装其他的工具函数的时候,也要记得才用此种方式吧。
🚀 文件夹结构如下:
05-数组的函数式编程(文件夹)
├─ lib
│ └─ arrayFuncs.js
├─ index.js
└─ package.json
如上述树形结构,需要在文件夹中运行npm init,然后给文件添加"type" = "module",如下:
- 这里对
type进行一个规范,要么是commonjs(node中),要么是module(es6模块化)
{
"name": "funcs",
...略
"type": "module",
"directories": {
"lib": "lib"
},
...略
}
🚀 arrayFuncs.js:
//forEach的实现
const forEach = (array, fn) => {
for (const value of array) {
fn(value);
}
};
//map的实现
const map = (array,fn)=>{
let result = [];
for(const value of array){
result.push(fn(value))
}
return result;
};
const arrayFuncs = {
map,forEach
}
export default arrayFuncs
- 通过一个
arrayFuncs的对象,将方法作为属性塞进去 - 通过
export default导出该对象
🚀 index.js中的使用:
import arrayFuncs from "./lib/arrayFuncs.js";
console.dir(arrayFuncs);
let arr1 = [1, 2, 3, 4, 5, 6];
arrayFuncs.forEach(arr1, (a) => {
return a + 1;
});
console.log(arr1);
console.log(arrayFuncs.map(arr1,(a)=>{
return a*a;
}));
运行后的结果依然如上图,没有变化。
2.filter方法:
其实filter函数大体上就是在map函数上做出一点小小的变化罢了。
//filter函数
const filter = (array,func)=>{
let result = [];
for(const value of array){
func(value) ? result.push(value):undefined
}
return result;
}
- 要善于利用把三元操作符用到赋值等操作中去,有利于提高代码的可读性
🚀 使用:
//filter函数的测试
let apressBooks = [
{
"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": []
},
{
"id": 333,
"title": "你不知道的js(下)",
"author": "Adam Freeman",
"rating": [4.0],
"reviews": []
},
{
"id": 444,
"title": "未来世界幸存者",
"author": "Adam Freeman",
"rating": [4.2],
"reviews": [{good : 14 , excellent : 12}]
}
];
var filterBooks = arrayFuncs.filter(apressBooks,function(book){
return book.rating[0] > 4.5;
});
console.log('我是评分高于4.5的书籍📚',filterBooks);
打印获取到的结果如下:
这样梳理过后,在以后使用过程中就不会出现问题,后续会继续进行数组的函数式编程的连接、reduce以及zip等