使用JavaScript怎么获取数组中的最大值或最小值?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
方法一:
//最小值
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;
}
console.log([55,38,7,19].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;
}
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);
运行结果:
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。