场景:js循环遍历有很多中方法,这次记录下forEach与some循环遍历的区别,以及在计算一个数组中被选中项的总和是多少
// forEach:循环一旦开始,中间无法停止
var forEachArr = ['小文','小李','小田','小夏','小孙'] forEachArr.forEach((item,index)=>{ console.log('forEach的Item:',item) if(item=='小田'){ console.log('小田的下标是:',index) } })
结果是:
//some:在找到对应项之后,可以通过return true固定的语法,来终止some循环
forEachArr.some((item,index)=>{ console.log('some的Item是:',item) if(item=='小夏'){ console.warn('找到小夏了oooooooooooooooooooo') return true } })
结果是:当找到目标值,就被return了,不会再往下执行了
//every:判断数组中,水果是否被选中
const everyArr=[ {id:'1',name:'苹果',state:true,price:10,count:1}, {id:'2',name:'火龙果',state:true,price:30,count:2}, {id:'3',name:'香蕉',state:true,price:20,count:6}, {id:'4',name:'桃子',state:true,price:40,count:8}, {id:'5',name:'橘子',state:false,price:10,count:1}, {id:'6',name:'橙子',state:false,price:10,count:1}, ] const result = everyArr.every(item=>item.state) console.log('数组中的水果是否全部被选中:',result)
结果:因为当前数组中含有没有被选中的,所以返回false
// filter + forEach
const everyArr=[ {id:'1',name:'苹果',state:true,price:10,count:1}, {id:'2',name:'火龙果',state:true,price:30,count:2}, {id:'3',name:'香蕉',state:true,price:20,count:6}, {id:'4',name:'桃子',state:true,price:40,count:8}, {id:'5',name:'橘子',state:false,price:10,count:1}, {id:'6',name:'橙子',state:false,price:10,count:1}, ] let amt = 0//总价 everyArr.filter(item=>item.state).forEach(item=>{ amt += item.price * item.count }) console.error('被选中水果的总价是:',amt)
结果:
// filter + reduce:(累加的结果,当前循环项)=>{},初始值)
const everyArr=[ {id:'1',name:'苹果',state:true,price:10,count:1}, {id:'2',name:'火龙果',state:true,price:30,count:2}, {id:'3',name:'香蕉',state:true,price:20,count:6}, {id:'4',name:'桃子',state:true,price:40,count:8}, {id:'5',name:'橘子',state:false,price:10,count:1}, {id:'6',name:'橙子',state:false,price:10,count:1}, ] const results = everyArr.filter(item=>item.state).reduce((amt,item)=>{ return amt+=item.price * item.count },0) console.log('使用filter + reduce计算出的总价是:',results)
结果: