1. 程式人生 > >高階函數簡述 js

高階函數簡述 js

div color class 高階函數 dev 代碼 font ron 編程

1、簡述

高階函數似乎是一種先進編程的的技術。然而,並不是。

高階函數其實就是將函數作為參數或者返回值的函數。其中作為參數的函數一般是回調函數。

2、例子

(1)最簡單的例子

大家都熟悉數組的sort方法。

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

    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0"
/> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>高階函數</title> </head> <body> <script type="text/javascript"> let arr = [1,2,4,3]; arr.sort((a,b)=>{return a-b}) console.log(arr)
</script> </body> </html>

sort方法的參數就是一個函數(回調函數),這個回調函數決定了如何比較數組中的任意兩個元素。

(2)字符換大寫

實現一:

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

    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0"
/> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>高階函數</title> </head> <body> <script type="text/javascript"> let arr = [abc, def], arrNew = []; for(let i = 0; i < arr.length; i++) { arrNew[i] = arr[i].toUpperCase() } console.log(arrNew) </script> </body> </html>

實現二:

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

    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>高階函數</title>
    </head>

    <body>
        <script type="text/javascript">
            let arr = [abc, def],
                arrNew = [];
            arrNew = arr.map(val => {
                return val.toUpperCase()
            })
            console.log(arrNew)
        </script>
    </body>

</html>

(3)高階函數實現

若代碼中出現重復或者類似的代碼,就可以使用高階函數。如產生一個包含數字的字符串:

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

    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>高階函數</title>
    </head>

    <body>
        <script type="text/javascript">
            let digits = ‘‘
            for (let i=0;i<10;i++) {
                digits += i
            }
            console.log(digits)
        </script>
    </body>

</html>

使用高階函數實現:

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

    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>高階函數</title>
    </head>

    <body>
        <script type="text/javascript">
            let digits = ‘‘
            function buildString(n, callback) {
                let val = ‘‘;
                for(let i = 0; i < n; i++) {
                    val += callback(i)
                }
                return val
            }
            digits = buildString(10, i => {
                return i
            })
            console.log(digits)
        </script>
    </body>

</html>

高階函數簡述 js