如何为数组取最大值与最小值。最笨的方法估计是这样:

 

代码
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;

}

 


如果你是引入类库进行工作,害怕类库也实现了同名的原型方法,我们可以在生成之前进行判断:

if (typeof Array.prototype['max'== 'undefined') {
    Array.prototype.max 
= function() {
        
//************略************* 
        }

}

 



但这两个扩展实现得的确不怎么样?!有什么原生的方法可以给我们用一用呢?John Resig巧妙地利用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)

}
[
123].max()// => 3 
[123].min()// => 1

 


 

 

posted on 2011-01-08 10:02  钱途无梁  阅读(1361)  评论(0编辑  收藏  举报