数组:筛选目标值并进行计算(filter,forEach,reduce)

216 阅读2分钟

应用情景:计算购物车中已勾选商品的价格

​ 方法1:Array.filter筛选,Array.forEach循环累加

    const arr = [
            {id:1,name:'商品1',state:true,price: 10,count:1},
            {id:2,name:'商品2',state:false,price: 80,count:2},
            {id:3,name:'商品3',state:true,price: 20,count:3},
        ]
    //需求:把购物车数组中,已勾选的水果(state:true),总价累加起来
    
    let amt = 0 //总价
    
    arr.filter(item => item.state).forEach(item=>{  
            //filter:筛选state值为true的商品,
            //forEach:遍历选中的商品并将价格累加
    
            amt +=item.price * item.count    //单价*数量
        })
	console.log(amt)   //打印总价

方法2:Array.filter筛选,Array.reduce()循环计算

    const arr = [
            {id:1,name:'商品1',state:true,price: 10,count:1},
            {id:2,name:'商品2',state:false,price: 80,count:2},
            {id:3,name:'商品3',state:true,price: 20,count:3},
        ]
        
    //arr.filter(item=>item.state).reduce((累加的结果,当前循环项)=>{},初始值)
    
    const result = arr.filter(item=>item.state).reduce((amt,item)=>{
                       return amt +=item.price*item.count
                },0)  //reduce除函数外,还接受一个初始值
    
   /* 因为reduce中只有一行代码,所以可以进行简写
   *const result=arr.filter(item=>item.state).reuce((atm,item)=>atm=item.price*item.count,0)
   */ 
   console.log(result)

相关知识点:

Array.filter()

效果:筛选出指定数组中符合条件的元素组成新的数组

array.filter(function(currentValue,index,arr), thisValue)

其中:

  • callback:数组中每个元素执行的函数,该函数可接受1-3个参数
  • currentValue:表示数组的当前元素项,必须的参数
  • index:当前元素的下标(索引) 可选
  • arr:当前元素所属的数组 可选
  • thisValue:表示执行回调函数callback()时的this指向。 可选
  • 返回值:返回一个含有所有满足条件的元素的新数组,无则返回空数组

1.Array.forEach

遍历数组

Array.forEach(callback(currentValue,index,arr),thisValue)

注意:虽然forEach内部是回调函数,但forEach本身为同步任务,在内部循环执行完毕后,才会进行下一行语法的执行

  • 其中:

    • callback:数组中每个元素执行的函数,该函数可接受1-3个参数

    • currentValue:表示数组的当前元素项,必须的参数

    • index:当前元素的下标(索引) 可选

    • arr:当前元素所属的数组 可选

    • thisValue:表示执行回调函数callback()时的this指向。 可选

      forEach()没有返回值

    var arr=[1,3,5,7,9]
    var res=arr.forEach(function(item,index){
        console.log(`数组第${index+1}个元素是${item}`)
    })
    console.log(res)  //undefine,forEach无返回值

forEach的缺陷:

  • forEach与for循环不同,即使找到某个满足条件的元素,也无法提前结束,return也不行

Array.reduce()

效果:接收一个函数作为累加器,对数组中的每个值进行计算,最终计算为一个值。

array.reduce(function(total, currentValue, currentIndex, arr), initialValue) 

其中:

  • function:数组中每个元素执行的函数,该函数可接受2-4个参数
  • total:循环前为initialValue(初始值),之后为每次循环返回的值(如:每次循环后某值累加的结果) 必须
  • currentValue:当前元素 必须
  • currentIndex:当前元素的索引 可选
  • arr:当前元素所属的数组对象。 可选
  • initialValue:传递给函数的初始值
  • 返回值:返回计算的结果