<!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>Vue自学:javascript高阶函数的使用</title>
    <title></title>
</head>
<body>
</body>
    <script type="text/javascript">
    //所谓的高阶函数,就是传递的参数里,可以传递函数,即function()
    //编程范式分为命令式编程和声明式编程
    //变成方式:面相对象编程(第一公民:对象)、函数式编程(第一公民:函数)
    //高阶函数:filter map reduce
    //filter 结果必须返回一个布尔值,假设返回的是个true时,函数内部会自动将回调中的n存入到数组中,当返回为false时,函数内部则会过滤掉这个n
    //需求1,在数组中取出<100的数字
    const nums = ['100','80','79','200','102','88']
    //普通的执行方法
    // let result = []
    // for(let item of nums){
    //     if(item<=100){
    //         result.push(item)
    //     }
    // }
    //filter 是一个高阶函数
    //函数的参数为一个函数
    //filter会自动创建一个新的数组
    //filter主要是对数组进行比较操作
    let result = nums.filter(function(n){
        return n<=100
    })
    console.log(result);
    //map 高阶函数
    //map 主要将数组整合起来运算操作
    let result1 = result.map(function(n){
        return n*2
    })
    console.log(result1);
    //reduce 高阶函数的使用
    //reduce 主要用于将数组整合操作
    let result2 = result1.reduce(function(preValue,n){
        return preValue+n
    },0)
    //第一次,preValue0 n200
    //第二次, preValue200 n160
    //第三次, preValue360 n158
    //第四次, preValue518 n176
    //结果为:518+176
    //使用链式写法
    let result3 = nums.filter(function(n){
        return n<=100
    }).map(function(n){
        return n*2
    }).reduce(function(preValue,n){
        return preValue+n
    },0)
    //使用箭头函数的写法
    let result4 = nums.filter(n=> n<=100).map(n=> n*2).reduce((pre,n) => pre + n , 0)
    console.log(result4)
    </script>
</html>
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号