一、问题
有时候,对于一个装满数字的数组,希望快速地得到其最大值、最小值分别是多少。真希望通过如下方式来取得:
var a = [1, 2, 3, 4];
alert("最大值:" + a.max());
alert("最小值:" + a.min());
只可惜JavaScript的数组对象没有自带此两种方法,有必要增强一下。
二、解决方案
利用JavaScript的Array对象的prototype对象进行添加:
//
// 给数组对象添加一个 min() 方法
//
Array.prototype.min = function () {
return Math.min.apply(null, this);
};
//
// 给数组对象添加一个 max() 方法
//
Array.prototype.max = function () {
return Math.max.apply(null, this);
};
三、立即试用!
点击这里运行