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

posted on 2014-03-18 15:31  挨踢前端  阅读(932)  评论(0编辑  收藏  举报

导航