5,vue过滤和高阶函数

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

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
  <style>
    .show1 {
      color: blue;
      cursor: pointer;
    }
  </style>
</head>

<body>
  <div id="app">
    <p>vue的过滤器</p>
    <div>价钱:{{getPrice(80)}}</div>
    <div>{{jishu()}}</div>

  </div>
</body>
<script src="vue.js"></script>
<script>
  new Vue({
    el: '#app',
    data: {
      books: [{
        id: 1,
        name: '高级编程',
        price: 80,
        count: 1
      }, {
        id: 1,
        name: '计算机基础',
        price: 50,
        count: 1
      }, {
        id: 1,
        name: '红宝书',
        price: 30,
        count: 2
      }, ],

    },
    computed: {

    },
    created: function () {},
    methods: {
      // 过滤器, 保留后面2位小数,  可以用methods 写方法来代替过滤器
      getPrice(price) {
        return '¥' + price.toFixed(2);
      },
      pp() {
        // 1,for普通遍历
        // let totalPre = 0;
        // for(let i = 0; i<this.books.length; i++){
        //   totalPre += this.books[i].price * this.books[i].count;
        // }

        // 2, for(let i of arr) for of来遍历
        let totaPri = 0;
        for (let item of this.books) {
          totaPri += item.price * item.count
        }
        return totaPri;

        // 3,reduce遍历
        // return this.books.reduce((pre, book) =>{
        //   return pre + book.price * book.count;
        // },0)
      },
 
      jishu() {
        // 高阶函数: filter, map, reduce
        let nub = [10, 20, 50, 103, 120, 150];

        // 1, 过滤小于100的数字
        let nub2 = nub.filter((n) => {
          // 返回一个条件成立的数据
          return n < 100;
        })

        // 2,对数组的值进行改变,返回新的值
        let newNub3 = nub2.map((item) => {
          return item * 2;
        })
       

        // 3,reduce()
        // 对数组中的所有内容进行汇总, 要么相乘,相加
        let total = newNub3.reduce((pre, cur) => {
          return pre + cur;
        }, 0)

        // 4,高阶写法
        let total2 = nub.filter((n) => {
          return n < 100;
        }).map((n) => {
          return n * 2;
        }).reduce((pre, n) => {
          return pre + n;
        }, 0)

        // let tot3 = nub.filter(n => n<100).map(n => n*2).reduce((pre, n) => pre+n);



      }
    }
  })
</script>

<script>



</script>

</html>

 

 
posted @ 2021-05-10 21:04  云悠  阅读(82)  评论(0编辑  收藏  举报