取数组最大值的几种方法

取数组最大值的几种方法

var arr = [7,2,0,-3,5];

apply()应用某一对象的一个方法,用另一个对象替换当前对象

1
2
var max = Math.max.apply(null,arr);
console.log(max)

由于 max()里面参数不能为数组,所以借助 apply(funtion,args)方法调用 Math.max(),function 为要调用的方法,args 是数组对象,当 function 为 null 时,默认为上文,即相当于 apply(Math.max,arr)

call()调用一个对象的一个方法,以另一个对象替换当前对象

1
2
var max1 = Math.max.call(null,7,2,0,-3,5)
console.log(max1)

call()与 apply()类似,区别是传入参数的方式不同,apply()参数是一个对象和一个数组类型的对象,call()参数是一个对象和参数列表

sort()+reverse()

1
2
3
//sort()排序默认为升序,reverse()将数组掉个
var max3 = arr.sort().reverse()[0];
console.log(max3)

sort()

1
2
3
4
5
//b-a 从大到小,a-b 从小到大
var max2 = arr.sort(function(a,b){
return b-a;
})[0];
console.log(max2)

pop()

1
2
var max3 = arr.sort().pop();
console.log(max3)
-------------本文结束感谢您的阅读-------------

本文标题:取数组最大值的几种方法

文章作者:Water

发布时间:2019年05月09日 - 15:05

最后更新:2023年08月01日 - 06:08

原始链接:https://water.buging.cn/2019/05/09/取数组最大值的几种方法/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

坚持原创技术分享,您的支持将鼓励我继续创作!