版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mm_hello11/article/details/82942699
方法一:
//为了防止同名的原型方法,可以在生成函数之前进行重名判断
if (typeof Array.prototype['max'] == 'undefined') {
//最小值
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;
}
}
方法二:
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
Math.max(x....)
参数 | 描述 |
---|---|
x | 0 或多个值。在 ECMASCript v3 之前,该方法只有两个参数。 |
方法三:
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"));//4
此方法类似于第二种方法,用的也是Math,但这种相当于把去取最小值和最大值封装在一个函数里了,通过传参数是max还是min来判定函数返回的是最小值和最大值。