美文网首页
求数组中的最大值(最小值)

求数组中的最大值(最小值)

作者: 迦叶凡 | 来源:发表于2019-04-14 12:20 被阅读0次

前言

这里记录下几种JavaScript求数组最大值(最小值)的方法。废话不多说,直接上代码。

正文

1.最原始的方法,for循环一一遍历

function max (array) {
   let result = array[0]
   for (let next of array) {
        result = Math.max(result, next)
   }
   return result
}
  1. reduce方法
function max (array) {
   let result = array.reduce(function (pre, next) {
     return Math.max(pre, next)
   })
   return result
}
  1. 排序方法(sort)
    这里多说一句:sort方法可以带一个function参数,根据返回值来决定升序还是降序排序。默认升序。
function max (array) {
   let arr = array.sort(function(a, b){
     if (a < b) {
       return -1
     } else if (a > b) {
       return 1
     } else {
       return 0
     }
   })
   let result = arr[arr.length - 1]
   return result
}

4.apply方法

function max (array) {
   let result = Math.max.apply(null, array)
   return result
}

5.ES6方法

function max (array) {
   let result = Math.max(...array)
   return result
}

相关文章

  • jsday02

    数组 数组求最大值 数组求最小值 数组拼接成字符串 反转数组 冒泡排序 阻止链接跳转 数组的一些方法

  • 线性表最值问题

    找最小值 找最大值 顺序表求最大值 顺序表求最小值 带头结点单链表求最大值 带头结点单链表求最小值 q是 最大值/...

  • 2019-05-14

    日志文本筛选-sort awk 求最大值: 求最小值: 求和: 求平均值: 求最大值 求最大值 求最小值 中位数

  • function

    求任意数组的最大值 求任意数组的最小值 //求任意范围数字和 求任意数字的总和 // type 检测参数数据类型...

  • 找出数组中的最大值最小值,最小值必须在最大值前面

    给一个数组,找出数组中的最大值最小值,最小值必须在最大值前面,也就是说最小值的下标必须比最大值的下标小。 要求时间...

  • 数组的应用--最值问题

    查找数组中的最大值、最小值: 打印结果:

  • 子数组最大和最小值的差大等小于给定值(h1:1.1)

    给定数组arr和整数num,求arr的连续子数组中满足:其最大值减去最小值的结果大于num的个数。 大于   这是...

  • leetcode 题解

    1. 关于旋转数组 旋转数组求最小值,最大值,以及任意值:https://leetcode.windliang.c...

  • python:numpy数组常用的统计函数

    数据准备: 求和 求均值 求中值 求最大值和最小值 求极值(最大值和最小值之差)、 6、标准差

  • 数组二

    ackage com.itheima_04;/* * 数组获取最值(获取数组中的最大值最小值) */public ...

网友评论

      本文标题:求数组中的最大值(最小值)

      本文链接:https://www.haomeiwen.com/subject/usmjwqtx.html