zoukankan      html  css  js  c++  java
  • JavaScript 获取数组中最大值、最小值

    笨方法

    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;
    }
    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;
    }

    巧方法

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

    Array.max = function( array ){   
        return Math.max.apply( Math, array );
    };
      
    Array.min = function( array ){    
        return Math.min.apply( Math, array );
    };

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

    Array.prototype.max = function(){  
       return Math.max.apply({},this);
    }
    Array.prototype.min = function(){  
       return Math.min.apply({},this);
    }

    原文章:http://erhuabushuo.is-programmer.com/posts/32298.html

  • 相关阅读:
    1.惨不忍睹凌乱的定时任务
    二维码名片
    给定的逗号分隔的数字字符串转换为Table
    sql 列集合转换成逗号分隔的字符类型
    linq 分组
    触发器
    整合思路、步骤
    整合注意事项
    配置文件
    Struts2的线程安全性
  • 原文地址:https://www.cnblogs.com/duanhuajian/p/3607861.html
Copyright © 2011-2022 走看看