js取陣列最大值的四種方式
阿新 • • 發佈:2018-12-05
var arr = [7,2,0,-3,5];
1.apply()應用某一物件的一個方法,用另一個物件替換當前物件
var max = Math.max.apply(null,arr);
console.log(max)
由於max()裡面引數不能為陣列,所以藉助apply(funtion,args)方法呼叫Math.max(),function為要呼叫的方法,args是陣列物件,當function為null時,預設為上文,即相當於apply(Math.max,arr)
2.call()呼叫一個物件的一個方法,以另一個物件替換當前物件
var max1 = Math.max.call(null,7,2,0,-3,5)
console.log(max1)
call()與apply()類似,區別是傳入引數的方式不同,apply()引數是一個物件和一個數組型別的物件,call()引數是一個物件和引數列表
3.sort()+reverse()
//sort()排序預設為升序,reverse()將陣列掉個
var max3 = arr.sort().reverse()[0];
console.log(max3)
4.sort()
//b-a從大到小,a-b從小到大
var max2 = arr.sort(function(a,b){
return b-a;
})[0];
console.log(max2)