整理:Javascript获取数组中的最大值和最小值的方法汇总

方法一:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//最小值
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;
}

如果你是引入类库进行开发,害怕类库也实现了同名的原型方法,可以在生成函数之前进行重名判断:

1
2
3
4
5
if (typeof Array.prototype['max'] == 'undefined') {
Array.prototype.max = function() {
... ...
}
}

方法二:

用Math.max和Math.min方法可以迅速得到结果。apply能让一个方法指定调用对象与传入参数,并且传入参数是以数组形式组织的。恰恰现在有一个方法叫Math.max,调用对象为Math,与多个参数

1
2
3
4
5
6
Array.max = function( array ){
return Math.max.apply( Math, array );
};
Array.min = function( array ){
return Math.min.apply( Math, array );
};

但是,John Resig是把它们做成Math对象的静态方法,不能使用大神最爱用的链式调用了。但这方法还能更精简一些,不要忘记,Math对象也是一个对象,我们用对象的字面量来写,又可以省几个比特了。

1
2
3
4
5
6
7
8
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

方法三:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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

方法四:

1
2
3
var a=[1,2,3,5];
alert(Math.max.apply(null, a));//最大值
alert(Math.min.apply(null, a));//最小值

多维数组可以这么修改:

1
2
3
4
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));//最小值
原文地址:https://www.cnblogs.com/yu-709213564/p/6189124.html