三个比较常用遍历数组的回调函数
目录
------arr.forEach((Element,index,Array)
------filter(Element,index,Array)
------Array.reduce((previousValue,currentValue,currentIndex)
------arr.forEach((Element,index,Array)
forEach可以收到三个参数,分别是:
Element:数组中正在处理的当前元素;
index:当前元素的索引号;
Array:正在操作的原数组
笔者经常用它来遍历数组对象,得到数组对象里的某个重要值(比如每个对象的id),下面的代码我觉得比较有代表性
let arr = [
{id:001, name: 'first', state:true},
{id:002, name: 'first', state:true},
{id:003, name: 'first', state:false},]
//可以用nanoid()来获取唯一的id值
arr.forEach((Ele,index)=>{
console.log(Ele.id);
// result 1 2 3,
//也可以获取name或者state属性值
})
map()和forEach的作用几乎一样,我这里就只给大家举个例子说一下他们的区别:map与forEach最大的区别就在于前者会分配内存空间存储新数据并返回,而后者不会返回数据:
let arr = [
{ id: 001, name: 'first', state: true },
{ id: 002, name: 'first', state: true },
{ id: 003, name: 'first', state: false },]
newArr = arr.forEach((item) => {
return item
})
console.log(newArr);
// result undefined
newArr = arr.map((item) => {
return item
})
console.log(newArr);
/***********************、
map的返回值是一个数组
result
(3)[{… }, {… }, {… }]
0: { id: 1, name: 'first', state: true }
1: { id: 2, name: 'first', state: true }
2: { id: 3, name: 'first', state: false }
length: 3
***********************/
注:(如果使用原生函数要多出一个参数thisArg,这个参数我没用过,不太清楚它的作用,会的大佬可以在评论区留言,大家相互学习共同进步 qqq)
------filter(Element,index,Array)
filter所接受的三个参数和forEach一样,就不再赘述了。不一样的是filter的回调返回的是布尔值,true则保留此元素,false则‘过滤’掉(网上的老师称为过滤函数是真的好记,形象生动)还是按照上面的模板上一段简单好理解的代码。可以看出只有满足条件式的id被留下来l
let arr = [
{ id: '001', name: 'first', state: true },
{ id: '002', name: 'first', state: true },
{ id: '003', name: 'first', state: false },]
arr = arr.filter((item)=>{
return item.id === '001';
})
console.log(arr);
/*
result
[{… }]
0: { id: '001', name: 'first', state: true }
length: 1
*/
------Array.reduce((previousValue,currentValue,currentIndex)
Array.reduce((previousValue,currentValue,currentValue)=>{
return xxx
},startValue)
previousValue:上一次调用 callback 时的返回值,即上一次的返回值
currentValue:数组中正在处理的元素
currentIndex: 数组中正在处理的元素的索引号
startValue: previousValue的初始值(不写startValue默认从索引号为0的元素开始)
逐个遍历数组元素,每一步都将当前元素的值与上一步的计算结果相加(上一步的计算结果 是当前元素之前所有元素的总和)直到没有元素相加则将最后一次相加的值返回给本函数
文字实在太枯燥了,直接用简单的代码比较好理解(偷懒还是用了一样的模板qaq)
let arr = [
{ id: '001', name: 'first', state: true },
{ id: '002', name: 'second', state: false },
{ id: '003', name: 'three', state: true },
{ id: '004', name: 'four', state: true },
]
// 返回数组中对象状态为true的对象个数
let count = arr.reduce((pre,current) => {
return pre + (current.state ? 1 : 0)
},0)
console.log(count);
// result------3
上面所有内容都是我在学习中的总结,文章质量不高,每个函数都有很多其它的用处,大佬们有兴趣拓展的话可以直接留言,有错误的地方也希望大家指出,一定改正!希望能相互帮助,共同进步!