使用JavaScript怎么获取数组中的最大值或最小值-创新互联
使用JavaScript怎么获取数组中的大值或最小值?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

方法一:
//最小值
Array.prototype.min = function(){
var min = this[0];
var len = this.length;
for(var i=1; i max){
max = this[i];
}
}
return max;
}
console.log([55,38,7,19].max()); 运行结果:

如果引用了别的类库进行开发,害怕类库也用了同名的原型方法,可以在生成函数之前可以进行重名判断:
if(typeof Array.prototype['max'] == 'undefined'){
Array.prototype.max = function(){...}
}方法二:
//最小值
Math.min.apply(Math,arr); //等效于 Math.min.apply({},arr)和Math.min.apply(null,arr);
//原本取得最小值的方法是Math.min(n1,n2,n3...), apply可以改变参数的传入形式,第一个参数是什么都不是很重要
//大值
var arr = [55,38,7,19];
console.log(Math.max.apply(Math,arr));运行结果:

多维数组可以先打散为一维数组再做以上处理。
var arr1 = [1,2,3,[5,6],[3,4,8]];
var arr2 = arr1.join(",").split(",");
var a = Math.min.apply(Math,arr2);
console.log(a);运行结果:

方法三:
var arr = [55,38,7,19];
function getMaxMin(arr,maxmin){
if(maxmin === "max"){
return Math.max.apply(Math,arr);
}else if(maxmin === "min"){
return Math.min.apply(Math,arr);
}
}
var a = getMaxMin(arr,"max");
console.log(a);
var b = getMaxMin(arr,"min");
console.log(b);运行结果:

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注创新互联行业资讯频道,感谢您对创新互联的支持。
文章题目:使用JavaScript怎么获取数组中的最大值或最小值-创新互联
文章路径:http://www.scyingshan.cn/article/degops.html


咨询
建站咨询
