reduce, filter, map, forEach 使用

number数组 求和

const arr = [1,2,3,5,6]
const summary = arr.reduce((pre,cur,index,array)=>{ return x = pre + cur },0)  // summary : 17

对象数组指定项 求和

const arr = [{name:"lisi",age:18},{name:"张三",age:43}]
const summary = arr.reduce((pre, next) => pre + next.age, 0)  // summary : 61

数组过滤指定数据

const arr = [{name:"lisi",age:17},{name:"张三",age:43}]
const underAgeArr = arr.filter(item=> item.age <= 18)  // underAgeArr [{name:"lisi",age:17}]

数组映射一份自己需要的镜像数据

const arr = [{name:"lisi",age:17},{name:"张三",age:43}]
const optionsList = arr.map(item=>{
  return {
    name:item.name,
    value: item.age
  }
})  // optionsList [{name:"lisi",value:17},{name:"张三",value:43}]

数组遍历,修改本数组数据

const arr = [{name:"lisi",age:17},{name:"张三",age:43}]
arr.forEach(item=>{
  item.underAge = item.age <= 18
})  // arr [{name:"lisi",age:17,underAge: true},{name:"张三",age:43, underAge: false}]

posted @ 2021-12-22 19:21  可乐雪碧芬达  阅读(45)  评论(0编辑  收藏  举报