This article will give you a detailed description of how to find the array and the maximum value in js. Next I will introduce several examples to you.
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 }; // Calculate 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 = [,]; Alert (arr. join ("+") + "=" + arr. sum (); // And: 141 In alert (arr. join ("|") + ", the maximum number is:" + arr. maxima (); // The maximum number is 45. </Script> |
In addition, a method is provided to evaluate the maximum and minimum values of an array.
The Code is as follows: |
Copy code |
// Calculate the maximum and minimum values in the array // ------ Method 1 -------------------------------------------- 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 2 ------------------------------------------ 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 3 ---------------------------------------------- Array. prototype. max = function (){ Return Math. max. apply ({}, this ); } Array. prototype. min = function (){ Return Math. min. apply ({}, this) } |