数组的遍历

遇到一个项目需要自己根据不同平台显示不同的页面和链接,所以自己写了一个数组,需要遍历数组

list: [ { id: 'czbguanwei', logo: require('../assets/chargeDis/chezhubang.png'), title: '百度推广官微', activeState: '车主邦北京已上线的珠海驿联电站', dec: '初秋送爽,车主邦为新能源汽车用户送上初秋福利!' } ]

一开始我想到了forEach遍历


this.platformList.forEach(item => {
      console.log(item.id)
      if (item.id === this.$route.params.id) {
        this.info = item
        console.log(item.title)
        window.zhuge.track(item.title)
      }
    })

但是这种遍历方式,break无效

为了性能;我选择了 for in


for (let idx in platformList) {
      if (platformList[idx].id === this.$route.params.id) {
        this.info = platformList[idx]
        window.zhuge.track(this.info.title)
        break
      }
    }

map也可以实现: map和foreach 都是不能return break结束循环,但是map可以return一个新的数组而且不改变原来的数组

platformList.map((item) => {
      if (item.id === this.$route.params.id) {
        this.info = item
      }
    })

filter


platformList.filter((item) => {
      if (item.id === this.$route.params.id) {
        this.info = item
        console.log(item)
        return item
      }
    })

every


platformList.every((item) => {
      if (item.id === this.$route.params.id) {
        this.info = item
        console.log(item)
        return item
      }
    })

every和filter的区别: filter()会返回所有符合过滤条件的元素;every()会判断是不是数组中的所有元素都符合条件,并且返回的是布尔值 every()与some()的区别是:前者要求所有元素都符合条件才返回true,后者要求只要有符合条件的就返回true

转载于:https://my.oschina.net/u/3608045/blog/1928407

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值