数组的some、every、reduce方法

1、some,用于通过判断条件获得数组中的某一项,相比于 foreach 而言,foreach 在循环得到结果之后不会终止循环,会一直循环到数组结束,浪费性能,而 some 则通过 return true 终止循环。详情如下。

const array = ['苹果','香蕉','梨','榴莲','桃子']
// forEach 用法
array.forEach((item, index)=>{
    if(item === '榴莲') {
        console.log(index)
    }
})
// some 用法
array.some((item, index) => {
    if(item === '榴莲') {
        console.log(index)
        return true
    }
})

 

2、every,用于数组中的每一项是否符合判断条件,返回布尔值,全部满足返回true,有一项不满足返回false。详情如下。

const array = [
    {name:"苹果",state:true},
    {name:"香蕉",state:false},
    {name:"梨",state:true},
    {name:"榴莲",state:true},
    {name:"桃子",state:true}
]

const result = array.every(item => item.state)
console.log(result) // false

 

3、reduce, 累加器,用于把每次循环结果累加起来

const array = [
    {name: "苹果", state: true, price: 10, count: 1},
    {name: "香蕉", state: false, price: 20, count: 2},
    {name: "梨", state: true, price: 30, count: 3},
    {name: "榴莲", state: true, price: 40, count: 4},
    {name: "桃子", state: true, price: 50, count: 5}
]
// 需求:计算勾选的水果总价
// 常规写法
let amt = 0 // 总价
array.filter(item => item.state).forEach(item => {
    amt += item.price * item.count
})

// reduce写法
// 语法 reduce((计算结果, 当前循环量) => { }, 初始值)
array.filter(item => item.state).reduce((amt, item) => {
    return amt += item.price * item.count
}, 0)
// 简写
array.filter(item => item.state).reduce((amt, item) => amt += item.price * item.count, 0)

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值