前言
课程内容来自视频链接 希望大家多多支持作者 本文记录用,防止遗忘
some循环
const arr = ['小红','大红','aaa','bbb']
arr.forEach((item,index)=>{
console.log('ok')
if(item=='aaa'){
console.log(index)
return
}
})
arr.some((item,index)=>{
console.log('ok')
if(item=='aaa'){
console.log(index)
return true
}
})
every循环
判断数组中的每一项是否都满足需求,满足返回true,不满足返回false
const arr= [
{id: 1, name: '西瓜', state: true},
{id: 2, name: '榴莲', state: true},
{id: 3, name: '草莓', state: true},
]
const result = arr.every(item => item.state==true)
console.log(result)
reduce循环
普通实现
const arr = [
{ id: 1, name: '西瓜', state: true, price: 10, count: 1 },
{ id: 2, name: '榴莲', state: false, price: 80, count: 2 },
{ id: 3, name: '草莓', state: true, price: 20, count: 3 },
]
let amt = 0
arr.filter(item => item.state).forEach(item => {
amt += item.price * item.count
})
console.log(amt)
reduce实现 reduce循环可以理解为累加器,把每次循环的结果累加起来
const arr = [
{ id: 1, name: '西瓜', state: true, price: 10, count: 1 },
{ id: 2, name: '榴莲', state: false, price: 80, count: 2 },
{ id: 3, name: '草莓', state: true, price: 20, count: 3 },
]
const amt=arr.filter(item => item.state).reduce((amt, item)=>{
return amt += item.price * item.count
}, 0)
console.log(amt)
|