How to obtain the maximum and minimum values for an array. The most stupid method is estimated to be like this:
Code
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;
}
If you are introducing a class library for work and are afraid that the class library has also implemented a prototype method of the same name, we can judge before the generation:
If (typeof Array. prototype ['max '] = 'undefined '){
Array. prototype. max = function (){
*************
}
}
But are these two extensions actually not very good ?! What native methods can be used for us? John resig cleverly uses the apply method to call native math. Max and math. Min methods to quickly obtain results. Apply allows a method to specify the call object and input parameters, and the input parameters are organized in arrays. It is precisely now that there is a method called math. Max, the calling object is math, and multiple parameters.
Array. max = function (array ){
Return Math. max. apply (Math, array );
};
Array. min = function (array ){
Return math. Min. Apply (Math, array );
};
However, John resig is a static method that makes them Math objects. It cannot be called using a chain that is a favorite of great gods. However, this method can be more streamlined. Don't forget that the math object is also an object. We can use the literal number of objects to write it, saving several bits.
Code
Array. prototype. max = function (){
Return Math. max. apply ({}, this)
}
Array. prototype. min = function (){
Return Math. min. apply ({}, this)
}
[1, 2, 3]. max () // => 3
[1, 2, 3]. min () // => 1