• js数组最大值max和最小值min


    比较数组中数值的大小是比较常见的操作,比较大小的方法有多种,比如可以使用自带的sort()函数,下面来介绍如下几种方法,代码如下:

    方法一:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    //最小值
    Array.prototype.min = function() {
    var min = this[0];
    var len = this.length;
    for (var i = 1; i < len; i++){
    if (this[i] < min){
    min = this[i];
    }
    }
    return min;
    }
    //最大值
    Array.prototype.max = function() {
    var max = this[0];
    var len = this.length;
    for (var i = 1; i < len; i++){
    if (this[i] > max) {
    max = this[i];
    }
    }
    return max;
    }

    如果你是引入类库进行开发,害怕类库也实现了同名的原型方法,可以在生成函数之前进行重名判断:

    1
    2
    3
    4
    5
    if (typeof Array.prototype['max'] == 'undefined') {
    Array.prototype.max = function() {
    ... ...
    }
    }

    方法二:

    用Math.max和Math.min方法可以迅速得到结果。apply能让一个方法指定调用对象与传入参数,并且传入参数是以数组形式组织的。恰恰现在有一个方法叫Math.max,调用对象为Math,与多个参数

    1
    2
    3
    4
    5
    6
    Array.max = function( array ){
    return Math.max.apply( Math, array );
    };
    Array.min = function( array ){
    return Math.min.apply( Math, array );
    };

    但是,John Resig是把它们做成Math对象的静态方法,不能使用大神最爱用的链式调用了。但这方法还能更精简一些,不要忘记,Math对象也是一个对象,我们用对象的字面量来写,又可以省几个比特了。

    1
    2
    3
    4
    5
    6
    7
    8
    Array.prototype.max = function(){
    return Math.max.apply({},this)
    }
    Array.prototype.min = function(){
    return Math.min.apply({},this)
    }
    [1,2,3].max()// => 3
    [1,2,3].min()// => 1

    方法三:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    function getMaximin(arr,maximin)
    {
    if(maximin=="max")
    {
    return Math.max.apply(Math,arr);
    }
    else if(maximin=="min")
    {
    return Math.min.apply(Math, arr);
    }
    }
    var a=[3,2,4,2,10];
    var b=[12,4,45,786,9,78];
    console.log(getMaximin(a,"max"));//10
    console.log(getMaximin(b,"min"));//04

    方法四:

    1
    2
    3
    var a=[1,2,3,5];
    alert(Math.max.apply(null, a));//最大值
    alert(Math.min.apply(null, a));//最小值

    多维数组可以这么修改:

    1
    2
    3
    4
    var a=[1,2,3,[5,6],[1,4,8]];
    var ta=a.join(",").split(",");//转化为一维数组
    alert(Math.max.apply(null,ta));//最大值
    alert(Math.min.apply(null,ta));//最小值

    以上内容是小编给大家分享的Javascript获取数组中的最大值和最小值的方法汇总,希望大家喜欢。

  • 相关阅读:
    timeout in asp.net
    ASP.NET_SessionId vs .ASPXAUTH why do we need both of them?
    Visual paradigm软件介绍
    OJ网站程序员必备
    c++异常详解
    C++STL之双端队列容器
    GPU的线程模型和内存模型
    C++ 中memset 勿要对类使用
    trait与policy模板技术
    C++标准库
  • 原文地址:https://www.cnblogs.com/chenmingchao/p/6382186.html
Copyright © 2020-2023  润新知