es6 数组方法总结 reduce map filter some every forEach

4 篇文章 0 订阅

数组常用方法总结

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
  </style>
</head>

<body>
  <div id="app">
    <h2>reduce计算数字总和-{{allPrice_reduce}}</h2>
    <h2>map计算所有的名字为数组-{{allName}}</h2>
    <h2>filter过滤出价格小于100的数组-{{allFilterPriceUnder100}}</h2>
    <h2>some判断数组的每一项id是否有大于100布尔值-{{IdIsOver100}}</h2>
    <h2>every判断数组的每一项id是否全部大于100布尔值-{{allIdIsOver100}}</h2>

  </div>
</body>
<script src="./vue.js"></script>
<script>
  Vue.config.productionTip = false
  let vue = new Vue({
    el: '#app',
    data() {
      return {
        books: [
          { id: 99, name: "西游记", price: 119 },
          { id: 106, name: "红楼梦", price: 19 },
          { id: 108, name: "水浒传", price: 109 },
          { id: 109, name: "三国", price: 179 },
        ]
      }
    },
    computed:{
      allPrice_reduce(){
        // es6 reduce  返回值为累加后的值 四个属性 1累加器(默认为数组第一个), 2当前值(默认为第二个),3当前值的index,4原数组 
        return this.books.reduce((acc,cur,curIndex,arr)=>{
          // return acc.price + cur.price      第二次的acc为计算后的数字 没有price属性 
          return (typeof(acc) === 'number' ? acc : acc.price) + cur.price
        })
      },
      // es6 map 返回值为新数组  item(当前值),index(当前值索引),arr(原数组)
      allName(){
        return this.books.map(item=>item.name)
      },
      // es6 filter 过滤数组 返回一个新数组   item(当前值),index(当前值索引),arr(原数组)
      allFilterPriceUnder100(){
        // 符合条件的会被放进新数组返回
        return this.books.filter(item=>item.price<100)
      },
      // es6 some 返回一个布尔值 有一个满足即为true   item(当前值),index(当前值索引),arr(原数组)
      IdIsOver100(){
        return this.books.some(item=>item.id>100)
      },
      // se6 every 返回一个布尔值 所有满足条件为true   item(当前值),index(当前值索引),arr(原数组)
      allIdIsOver100(){
        return this.books.every(item=>item.id>100)
      },
      // es6 forEach  遍历数组  
      allForEach(){
        return this.books.forEach((item,index)=>{
          console.log(`${index}--${item.name}`)
        })
      }
    }
  })
</script>

</html>

在这里插入图片描述
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值