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>