JS常用高阶函数
filter(过滤函数)
回调函数必须返回一个bool值,函数返回一个新的数组,不会改变原数组
用法:查询小于等于30的值
const list = [10, 20, 30, 40, 50];
console.log(list.filter(item=>{
return item <= 30 // bool值
}));
console.log(list);
print:
[10, 20, 30]
[10, 20, 30, 40, 50]
更多用法:将含有pid的数组快速组成一颗含有children的树结构
const list = [
{ id: 1, name: 'Node 1', pid: 0 },
{ id: 2, name: 'Node 2', pid: 1 },
{ id: 3, name: 'Node 3', pid: 1 },
{ id: 4, name: 'Node 4', pid: 2 },
{ id: 5, name: 'Node 5', pid: 0 }
];
// 构建树
function buildTree(items, parentId = 0) {
return items.filter(item => item.pid === parentId).map(item => ({
...item,
children: buildTree(items, item.id)
}));
}
console.log(buildTree(list));
print:
[
{
"id": 1,
"name": "Node 1",
"pid": 0,
"children": [
{
"id": 2,
"name": "Node 2",
"pid": 1,
"children": [
{ "id": 4, "name": "Node 4", "pid": 2, "children": [] }
]
},
{ "id": 3, "name": "Node 3", "pid": 1, "children": [] }
]
},
{ "id": 5, "name": "Node 5", "pid": 0, "children": [] }
]
map(重新生成列表项)
回调函数返回一个值,函数返回一个新的数组,不会改变原数组,新数组大小和原数组一样
用法:将原有项都乘0.01
const list = [10, 20, 30, 40, 50];
console.log(list.map(item => item * 0.01));
console.log(list);
print:
[0.1, 0.2, 0.3, 0.4, 0.5];
[10, 20, 30, 40, 50];
更多用法:快速生成1到100的数组
const list1 = Array(100).fill(0).map((_,index) => index + 1));
const list2 = Array.from({ length: 100 }, (_, i) => i + 1); // 其他方法
console.log(list1);
console.log(list2);
print:
[1,2,3,4,...100];
[1,2,3,4,...100];
reduce(汇总处理函数)
对数组中所有的内容进行汇总,包含回调函数和初始值两个参数
用法:计算数组中数的总和
const list = [10, 20, 30, 40, 50];
console.log(list.reduce((pre,n)=>{
return pre + n; // pre为上一次返回的值,n为当前列表值
},0));
console.log(list);
print:
150;
[10, 20, 30, 40, 50];
其他用法:展开树
const tree = [
{
"id": 1,
"name": "Node 1",
"pid": 0,
"children": [
{
"id": 2,
"name": "Node 2",
"pid": 1,
"children": [
{ "id": 4, "name": "Node 4", "pid": 2, "children": [] }
]
},
{ "id": 3, "name": "Node 3", "pid": 1, "children": [] }
]
},
{ "id": 5, "name": "Node 5", "pid": 0, "children": [] }
]
const list = tree.reduce((pre, cur) => {
let items = []
const handleChild = (childs) => {
if(childs.length){
items = [...items, ...childs]
childs.forEach(item => {
handleChild(item.children);
if(item.children)
delete item.children
})
}
}
handleChild(cur.children)
if(cur.children)
delete cur.children
return [...pre, cur, ...items]
},[])
console.log(list);
print:
[
{ id: 1, name: 'Node 1', pid: 0 },
{ id: 2, name: 'Node 2', pid: 1 },
{ id: 3, name: 'Node 3', pid: 1 },
{ id: 4, name: 'Node 4', pid: 2 },
{ id: 5, name: 'Node 5', pid: 0 }
];