数组的some()、forEach()、every()、reduce()方法的使用

some()方法查询到了符合条件的值,通过return true固定语法可以终止循环

forEach()方法循环一旦开始无法在中间中止,直到循环结束

every()方法全部符合条件返回true,反之返回false

reduce()方法

使用代码案例:

<template>
  <div class="array">
    <h2>数组的方法</h2>
    <!-- some()方法 -->
    <p>数组:{{ arr }}</p>
    <p>下标:{{ ind }}</p>
    <button @click="findArr">查询数组中3的下标</button>
    <!-- 判断是否全选 true-是 false-不是 every()方法 -->
    <p>是否全选:{{ selectAll }}</p>
    <button @click="IsSelect">判断是否全选</button>
    <!-- reduce()方法基础应用 -->
    <!-- 需求:把已选的商品的价格累加起来 -->
    <p>总价:{{ totalPrice }}</p>
    <button @click="sum">计算总价</button>
  </div>
</template>

<script type="text/ecmascript-6">
export default {
    data () {
        return {
            arr:[1,2,3,4,5,6,7],
            ind:0,
            msgArr:[
                {id:1,name:'辣条',state:true,price:10,count:5},
                {id:2,name:'面条',state:true,price:5,count:10},
                {id:3,name:'薯片',state:false,price:8,count:6},
                {id:4,name:'雪糕刺客',state:true,price:52,count:2}
            ],
            // 是否全选
            selectAll:'',
            // 总价
            totalPrice:0
        }
    },
    methods: {
        // forEach()和some()方法
        findArr(){
            // 非常消耗性能,循环一旦开始无法在中间终止
            // this.arr.forEach((item,index) => {
            //     if (item===3) {
            //         this.ind=index
            //     }
            // });

            // some()方法在找到符合条件的数据通过返回return true可以中止循环遍历
            this.arr.some((item,index)=>{
                if (item===3) {
                    this.ind=index
                    return true
                }
            })
        },
        // every()方法
        IsSelect(){
            // 全部为true就返回true,否则返回false,判断是否全选
            this.selectAll=this.msgArr.every(item=>item.state)
        },
        // 计算已选商品总价  reduce()
        sum(){
            // 方法一
            // this.msgArr.filter(item=>item.state==true).forEach((item)=>{
            //     this.totalPrice+=item.price*item.count
            // })
            // 方法二
            // reduce((tp,item)=>{},0) 参数tp为每循环一次拿到的结果,参数item是循环项,0为初始值赋给tp
            this.totalPrice=this.msgArr.filter(item=>item.state==true).reduce((tp,item)=>{
                return tp+=item.price*item.count
            },0)
        }
    }
}
</script>

<style lang="scss" scoped></style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值