5. vue常用高階函數及綜合案例

一. 常用的數組的高階函數

 假設, 現在有一個數組, 我們要對數組做如下一些列操作

1. 找出小於100的數字:
2. 將小於100的數字, 全部乘以2: 
3. 在2的基礎上, 對所有數求和:

通常我們會怎麼做呢? 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <p>找出小於100的數字:</p>
    <p>將小於100的數字, 全部乘以2: </p>
    <p>對所有數求和:</p>

    <button @click="getNum()">計算</button>
</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: "#app",
        data: {
            nums: [10, 20, 100, 30, 320, 55, 80, 210],
            num1:0,
            num2:0,
            num3:0
        },
        methods: {
            getNum(){
                // 1. 找出<100的數字
                let newNum1 = []
                for(let  num of this.nums) {
                    if (num < 100) {
                        newNum1.push(num)
                    }
                }
                this.num1=newNum1
                console.log(newNum1)


                // 2. 對小於100的數字*2
                let newNum2 = []
                for(let num of newNum1) {
                    newNum2.push(num * 2)
                }
                this.num2 = newNum2
                console.log(newNum2)

                // 3. 對小於100的數字*2後求和
                let newNum3 = 0;
                for(let num of newNum2) {
                    newNum3 += num
                }
                this.num3 = newNum3
                console.log(newNum3)
            }
        }
    })
</script>
</body>
</html>

在上面的demo中, 我們全部都是使用循環來進行計算, 並且最後達到了我們想要的效果. 點擊計算按鈕, 查看計算結果:

 

 

在js高階函數裡面, 有一些高階函數是可以直接計算得到上面的效果的. 下面主要介紹三個高階函數

  • filter
  • map
  • reduce 

1. filter函數

filter()方法會創建一個新數組,原數組的每個元素傳入回調函數中,回調函數中有return返回值,若返回值為true,這個元素保存到新數組中;若返回值為false,則該元素不保存到新數組中;原數組不發生改變。

  • 語法: array.filter(function(currentValue,index,arr), thisValue)
  • 參數

  

舉例1: 返回數組中<100的元素   

getNums() {
    // 來看看filter的用法
   let num1 = [10 ,20, 100, 30, 320, 55. 80, 210] let newNum1 = this.nums.filter(function (num) { return num
< 100; }) console.log(newNum1) }
  • filter()函數的入參是一個function, 出參是一個新的數組
  • function函數也有參, 這裡只傳入了第一個入參, 表示: 循環遍歷時的數組元素. 
  • function的返回值類型是true或false, 如果返回結果是true, 則返回新數組中有這個元素, 返回結果是false, 則返回新數組中沒有這個元素

 

舉例2: 利用filter,可以巧妙地去除Array的重複元素:

filter()接收的回調函數,其實可以有多個參數。通常我們僅使用第一個參數,表示Array的某個元素。回調函數還可以接收另外兩個參數,表示元素的位置和數組本身:

let nums = [10, 20, 100, 30, 320, 55, 80, 210, 20, 55, 320]
let newNum2 = this.nums.filter(function(element, index, self) {
    return self.indexOf(element) == index
})

運行結果

 [10, 20, 100, 30, 320, 55, 80, 210]

去除重複元素依靠的是indexOf總是返回第一個元素的位置,後續的重複元素位置與indexOf返回的位置不相等,因此被filter濾掉了。

 

2. map函數

方法返回一個新數組,新數組中的每一個元素為原始數組對應每一個元素調用函數處理後的值;不會對空數組進行編輯,不改變原來的數組。

  • 語法: array.every(function(item,index,array){})
  • 參數:

    

 

 舉例1: 求數組中所有元素*2後的數組

let nums = [10, 20, 100, 30, 320, 55, 80, 210, 20, 55, 320]
let newNum1 = this.nums.map(function (num) {
    return num * 2;
})

console.log(newNum1)

輸出結果:

[20, 40, 200, 60, 640, 110, 160, 420, 40, 110, 640]

 

3. reduce函數

reduce() 方法接收一個函數作為累加器,reduce 為數組中的每一個元素依次執行回調函數,數組中被刪除或從未被賦值的元素不處理. 

  • 語法: arr.reduce(callback,[initialValue])
  • 參數

 

 

案例1: 求一個數組的和

// reduce的用法
let nums = [10, 20, 100, 30, 320, 55, 80, 210, 20, 55, 320]
let newNum1 = this.nums.reduce(function (total, num) {
    return num + total;
}, 0)
console.log(newNum1)

 

二. 綜合案例1

結合filter, map, reduce三個函數, 獲取數組中<100的元素, 然後對這些元素同意*5, 最後求*5後的所有元素的和

 // reduce的用法
let nums = [10, 20, 100, 30, 320, 55, 80, 210, 20, 55, 320]
let newNum1 = this.nums.filter(function (number) {
    return number < 100
}).map(function (number) {
    return number * 5
}).reduce(function (total, num) {
    return num + total;
}, 0)
console.log(newNum1)

輸出結果: 1220

 

 

 

其實還有更簡單的演算法, lambda表達式 

// reduce的用法
let nums = [10, 20, 320]
let newNum11 =
nums.filter(num => num < 100).map(num => num * 5, this).reduce((total, num) => total + num)
console.log(newNum11)

執行結果: 150

 

三.綜合案例2

顯示一個列表, 選中那個那個變色, 使用vue實現

 

 

可以思考兩分鐘, 看看, 如何來設計.

在vue中, 這個過程將非常簡單

  • 第一步: 定義了一個isCurrentIndex用來記錄當前選中元素的下標.
  • 第二步: 在class屬性中設置 :isCurrentIndex == index. 表示選中元素的下標顯示紅色, 其他不顯示紅色.
  • 第三步: 定義一個click事件, 每次點擊事件, 修改選中的下標值

 程式碼如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .action {
            color: red;
        }
    </style>
</head>
<body>
<div id="app">
    <ul>
        <li v-for="(item, index) in languages" :class="{action:isCurrentIndex == index}" @click="changeCurrentIndex(index)"> {{index}}--{{item}}</li>
    </ul>
</div>

<script src="../js/vue.js"></script>
<script>
    var app = new Vue({
        el: "#app",
        data: {
            languages: ["java", "php", "python", "go", "c語言"],
            isCurrentIndex:0
        },
        methods: {
            changeCurrentIndex(index) {
                this.isCurrentIndex = index
            }
        }
    });
</script>
</body>
</html>

 

 四. 綜合案例3

我們要做一個表格, 具體內容如下

 

 

 主要有哪些東西呢?

  1. 有n本書, 書有書名, 出版日期, 價格, 數量, 操作
  2. 價格保留兩位小數, 數量可增減, 最多減到0,
  3. 操作可以刪除表格 ,當表格沒有數據時顯示無數據
  4. 隨時計算總價格. 

 下面來看看這個程式碼如何實現, 結合我們之前學過的js高階函數

第一步: 定義了n本書, 放在vue的data屬性裡面

data: {
    books: [
        {name:"java設計模式", publishDate:"1998-10-21", price: 58.00, count: 1},
        {name:"go語言實戰分析", publishDate:"2018-5-12", price: 70.00, count: 1},
        {name:"vue深入淺出", publishDate:"2019-08-09", price: 46.89, count: 1},
        {name:"jquery實戰", publishDate:"2014-02-29", price: 39.98, count: 1}
    ],
    total: 0
},

定義了一個總價格, 用來保存計算後的總價格

 

第二步: 畫table

<div id="app">
    <table border="1">
        <thead>
            <tr>
                <td>序號</td>
                <td>書名</td>
                <td>出版日期</td>
                <td>價格</td>
                <td>購買數量</td>
                <td>操作</td>
            </tr>
        </thead>

        <tbody v-if="books.length==0">
            <tr>
                <td colspan="6" >沒有數據</td>
            </tr>
        </tbody>

        <tbody v-else>
            <tr v-for="(item, index) in books" >
                <td>{{index+1}}</td>
                <td>{{item.name}}</td>
                <td>{{item.publishDate}}</td>
                <td>{{item.price| priceUnit}} </td>
                <td>
                    <button @click="sub(index)">-</button>
                    {{item.count}}
                    <button @click="add(index)">+</button>
                </td>
                <td>
                    <button @click="del(index)">刪除</button>
            </tr>
        </tbody>
    </table>
    <label id="sum">總價: {{getTotal() | priceUnit}} </label>
</div>

在這裡我們循環遍歷了data數據, 然後對價格進行了處理, 增加了單位, 對數量增加了增減的button. 最後定義了一個刪除功能

第三步. 使用過濾器格式化價格

在對價格進行格式化的時候, 使用了管道符.這是過濾器的寫法. 不加過濾器之前, 價格是58. 加了過濾器之後是: $58.00, 增加了一個美元符號, 價格保留兩位小數

因為不止有一個地方會用到加單位, 所以, 我們將其定義為一個方法. 如下寫法

filters: {
    priceUnit(price) {
        return "$" + price.toFixed(2)
    }
}

這裡定義了過濾器的寫法. 類似於methods. 裡面定義一個方法. 其實這個方法可不可以放在methods中呢? 也可以, 但是放在filters有一個好處. 可以使用管道符寫法

<td>{{item.price | priceUnit}} </td>

使用過濾器, 會自動將 | 前面的值作為參數傳遞給priceUnit

第四步: 定義methods, 對圖書數量進行增減, 且做少不能少於0

sub(index) {
    if (this.books[index].count <= 0) {
        this.books[index].coun = 0;
    } else {
        this.books[index].count --;
    }
},
add(index) {
    this.books[index].count ++;
},

這個就不多說了, 普通函數寫法

第五步: 計算總額

計算總額有多種寫法, 常規寫法

getTotal() {
    let totalPrice = 0;
    for(let i = 0; i < this.books.length; i++) {

        totalPrice += this.books[i].price * this.books[i].count;
    }
    
    return totalPrice;
},

循環遍歷books, 價格和數量乘積的和

推薦使用js的高階函數

getTotal() {
    // 使用數組的高階函數計算每種書的價格總和
    return this.books.map((book)=>book.price * book.count).reduce((total,num) => total + num)
},

在回顧一下

  • map是對數組的每一個元素執行操作
  • reduce是對數組中所有元素求和

 第六步: 刪除表格行

del(index){
    this.books.splice(index,1)
}

刪除行, 使用splice刪除指定的data中的元素, 就可以了

 

Tags: