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>

 

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章