代码如下 |
复制代码 |
<script type="text/javascript">
//求和
Array.prototype.sum = function ()
{
for (var sum = i = 0; i < this.length; i++)sum += parseInt(this[i]);
return sum
};
//求最大值
Array.prototype.maxima = function ()
{
for (var i = 0, maxValue = Number.MIN_VALUE; i < this.length; i++)parseInt(this[i]) > maxValue && (maxValue = this[i]);
return maxValue
};
//应用
var arr = [1,21,3,4,22,45,6,7,32];
alert(arr.join("+") + "=" + arr.sum()); //和:141
alert(arr.join("|") + "中, 最大的数是:" + arr.maxima()); //最大数:45
</script>
|
另外附一个求数组最大值与最小值的方法
代码如下 |
复制代码 |
//求数组中最大值,最小值
//------ 方法一--------------------------------------------
Array.prototype.max=function(){
var r=this.sort(function(a,b){return a-b;})
return r[r.length-1];
}
Array.prototype.min=function(){
var r=this.sort(function(a,b){return a-b;})
return r[0];
}
//-----方法二------------------------------------------
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;
}
//----方法三----------------------------------------------
Array.prototype.max = function(){
return Math.max.apply({},this);
}
Array.prototype.min = function(){
return Math.min.apply({},this)
}
|
|