Comparing the size of values in an array is a relatively common operation. There are many ways to compare sizes. For example, you can use the built-in sort() function. Here are the following methods. The code is as follows:
Method 1:
//最小值 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() { var max = this[0]; var len = this.length; for (var i = 1; i < len; i++){ if (this[i] > max) { max = this[i]; } } return max; }
If you are introducing a class library for development, and you are afraid that the class library also implements a prototype method with the same name, you can check the duplicate name before generating the function:
if (typeof Array.prototype['max'] == 'undefined') { Array.prototype.max = function() { ... ... } }
Method 2:
Use Math.max and Math.min methods to get results quickly. Apply allows a method to specify the calling object and the incoming parameters, and the incoming parameters are organized in the form of an array. There is now 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 makes them static methods of the Math object, and cannot use the chain call that the master loves most. But this method can be more streamlined. Don't forget that the Math object is also an object. We can save a few bits by writing it in the literal value of the object.
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
Method 3:
function getMaximin(arr,maximin) { if(maximin=="max") { return Math.max.apply(Math,arr); } else if(maximin=="min") { return Math.min.apply(Math, arr); } } var a=[3,2,4,2,10]; var b=[12,4,45,786,9,78]; console.log(getMaximin(a,"max"));//10 console.log(getMaximin(b,"min"));//04
Method 4:
var a=[1,2,3,5]; alert(Math.max.apply(null, a));//最大值 alert(Math.min.apply(null, a));//最小值
Multidimensional arrays can be modified like this:
var a=[1,2,3,[5,6],[1,4,8]]; var ta=a.join(",").split(",");//转化为一维数组 alert(Math.max.apply(null,ta));//最大值 alert(Math.min.apply(null,ta));//最小值
The above content is a summary of Javascript methods for obtaining the maximum and minimum values in an array shared by the editor. I hope you will like it.