方法一、遍歷數組
var tmp = new Array(1,12,4,124.45,8,99998,456);
var max = tmp[0];
for(var i=1;i<tmp.length;i++){
if(max<tmp[i])max=tmp[i];}
方法二、使用apply方法,方法有兩個參數,用作 this 的對象和要傳遞給函數的參數的數組。(http://www.w3school.com.cn/js/pro_js_inheritance_implementing.asp)可以為方法指定調用對象與傳入參數,並且可以讓傳入的參數以數組的形式組織。
Math.Max.Apply(Math,tmp);
也可以寫成
Math.Max.Apply({},tmp);的簡寫形式
總:
兩個方法都可以作為對象方法擴展存在,例如
Array.prototype.max=function(){ 方法體 } //prototype可以像對象添加屬性或方法(http://www.w3school.com.cn/js/jsref_prototype_boolean.asp)
調用的時候就成了
var tmp = new Array(1,12,4,124.45,8,99998,456);
tmp.max();//99998
