一、借助apply(),获得最大值
var arr = [1, 2, 3, 4, 5, 6] var max = Math.max.apply(null,arr); console.log(max) //6
由于max()里面参数不能为数组,所以借助apply(funtion,args)方法调用Math.max(),function为要调用的方法,args是数组对象,当function为null时,默认为上文,即相当于apply(Math.max,arr)
二、借助call(),获得最大值
var arr = [1, 2, 3, 4, 5, 6] var max1 = Math.max.call(null,7,2,0,-3,5) console.log(max1)
call()与apply()类似,区别是传入参数的方式不同,apply()参数是一个对象和一个数组类型的对象,call()参数是一个对象和参数列表
三、sort()+reverse()
var arr = [1, 2, 3, 4, 5, 6] var max3 = arr.sort().reverse()[0]; console.log(max3)
sort()排序默认为升序,reverse()将数组掉个
四、sort()
var arr = [1, 2, 3, 4, 5, 6] var max2 = arr.sort(function(a,b){ return b-a; })[0]; console.log(max2)
b-a从大到小,a-b从小到大