| The code is as follows |
Copy Code |
<script type= "Text/javascript" >
Sum Array.prototype.sum = function () { for (var sum = i = 0; i < this.length; i++) sum + + parseint (this[i]); return sum }; Find the maximum value 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 }; Application var arr = [1,21,3,4,22,45,6,7,32]; Alert (Arr.join ("+") + "=" + Arr.sum ()); And: 141 Alert (Arr.join ("|") + ", the largest number is:" + Arr.maxima ()); Maximum number: 45 </script> |
Another method for finding the maximum and minimum value of an array
| The code is as follows |
Copy Code |
| To find the maximum value in an array, the minimum value ------Method One-------------------------------------------- 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]; } -----Method Two------------------------------------------ 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; } ----Method Three---------------------------------------------- Array.prototype.max = function () { Return Math.max.apply ({},this); } Array.prototype.min = function () { Return Math.min.apply ({},this) } |