你的位置:首页 > 信息动态 > 新闻中心
信息动态
联系我们

算法函数式编程的几种基本方法

2021-12-5 21:20:10

请添加图片描述

//找出数组中的最小值
        let arr = [30, 34, 23, 45, 90, 10]
        //方法一
        var findMinNums = function (arr) {
            let minNums = arr[0]
            for (var i = 1; i < arr.length; i++) {
                if (minNums > arr[i]) {
                    minNums = arr[i]
                }
            }
            return minNums
        }
        console.log(`findMinNums`, findMinNums(arr))
        //方法二
        const min_ = function (arr) {
            return Math.min(...arr)
        }
        console.log(min_(arr));
        //箭头函数
        const min2_ = arr => Math.min(...arr)
        console.log(min2_(arr));
        //二位数组展平成一位数组
        const arr2 = [[1, 2, 3, 4], [12, 34, 78], [88]]
        const mergeArr = function (arr) {
            let res = [], len = arr2.length, k = 0
            for (var i = 0; i < len; i++) {
                for (var j = 0; j < arr2[i].length; j++) {
                    res[k++] = arr2[i][j]
                }
            }
            return res
        }
        console.log(mergeArr(arr2));
        //展平数组的方式二
        const mergeArr2 = function (arr) {
            debugger
            return arr.reduce((p, n) => {
                return p.concat(n)
            })
        }
        console.log(mergeArr2(arr2));