Example of adding a method (sum, maximum) to an array using Javascript

Source: Internet
Author: User

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)
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.