Javascript中的Math.max方法可以求出給定參數中最大的數。
> Math.max('1','2','3.1','3.2') < 3.2
> Math.min(1,0,-1)
< -1
但如果是數組,就不能這樣調用了。
此時就用到了apply方法:
apply 方法 (Function) (JavaScript)
調用函數,並用指定對象替換函數的 this 值,同時用指定數組替換函數的參數。
apply([thisObj[,argArray]])
thisObj
可選。 要用作 this 對象的對象。
argArray
可選。 要傳遞到函數的一組參數。
巧妙地使數組也可以調用Math.max和Math.min。
> Math.max.apply(null, ['1','2','3.1','3.2']) < 3.2 > Math.min.apply(null, [1,0,-1])
< -1