js中数组求最大值的方法

一.擂台思想

二.通过Math.max方法

三.数组的reduce方法



擂台:

        let arr = [4, 49, 498, 4984, 984, 984, 94, 98, 498, 4];
        // 擂主
        let max = arr[0];
        for (let i = 1; i < arr.length; i++) {
            // 跟擂主比较,arr[i]大就当擂主
            max = max > arr[i] ? max : arr[i]
        };
        console.log(max);

Math.max()的两种方法

        console.log(Math.max.apply(null, arr));
        console.log(Math.max(...arr));

数组的reduce()方法

        arr.reduce((num1, num2) => {
            return num1 > num2 ? num1 : num2;
        })

当然还有其他方法,我这里只列举出几种简单的

猜你喜欢

转载自blog.csdn.net/Motion_zq/article/details/124828578
今日推荐