今天查到數組的sort函數可以接受自訂比較函數,這真是一件妙事兒。
這樣對(數字類型表示範圍以內的)數字進行排序就變得極為簡單了。
var myArray = [-80,-13.888,-10,-9.6,-9.4,-1,2,2,3,5.823,7.999,20,0,22,55,312]; iJs.put(myArray.sort(function(a,b){return a-b}));
調試資訊:
-80,-13.888,-10,-9.6,-9.4,-1,0,2,2,3,5.823,7.999,20,22,55,312
如果想降序,a-b改為b-a即可:
var myArray = [-80,-13.888,-10,-9.6,-9.4,-1,2,2,3,5.823,0,7.999,20,22,55,312]; iJs.put(myArray.sort(function(a,b){return b-a}));//此處為b-a
調試資訊:
312,55,22,20,7.999,5.823,3,2,2,0,-1,-9.4,-9.6,-10,-13.888,-80
構造返回比較函數的函數,可以達到更為靈活的目的。為此我寫了一個一維二維數組通用的排序函數如下(未經充分測試,如用於生產,最好再測一下啊):
//類型相同則比大小,升降由option的第一個參數指定 //類型不同則比類型,升降由option的第二個參數指定 //如果是對象或數組,則按name指定屬性或元素參與排序 //比大小結果相同則按照secondby指定的規則排序 var by = function(name,option,secondby){ return function(o,p){ var a,b; var sign=1;//調節順序 var r;//儲存傳回值 //如果是對象或數組,則按name指定屬性或元素參與排序 if(o && typeof o === 'object'){ a = o[name]; }else{ a = o; } if(p && typeof p === 'object'){ b = p[name]; }else{ b = p; } if(typeof a === typeof b){ //升降由option的第一個參數指定 switch(option[0]){ case "desc" : sign = 1; break; case "asc" : sign = -1; break; default: sign = 1;//預設 } }else{ //類型不同則比類型 a = typeof a; b = typeof b; //升降由option的第二個參數指定 switch(option[1]){ case "desc" : sign = 1; break; case "asc" : sign = -1; break; default: sign = 1;//預設 } } if(a === b){ //遞迴支援多個參數排序(20121231補充:如果傳進來不是by則不是遞迴) r = typeof secondby === "function" ? secondby(o,p):0; }else if(a<b){ r = 1*sign; }else{ r = -1*sign; } return r; } }//判斷是否數組 var is_array = function(value){ return value && //有值 typeof value === "object" && //typeof查出類型為object typeof value.length === "number" && //length屬性是number類型 typeof value.splice === "function" && //有splice方法 !(value.propertyIsEnumerable("length"))//length是一個不可枚舉的屬性 } //輸出二維數組
// http://www.bianceng.cn var puts = function(myObj){ for(var i=0;i<myObj.length;i+=1){ var tmp = ""; if(is_array(myObj[i])){ for(var j=0;j<myObj[i].length;j+=1){ tmp = tmp + myObj[i][j] + ","; } }else{ for(name in myObj[i]){ tmp = tmp + name + ":" + myObj[i][name] + ","; } } iJs.put(tmp); }}var myArray=new Array(); //例1 myArray = [ {"a":1,"b":1,"c":1}, {"a":3,"b":3,"c":1}, {"a":3,"b":4,"c":1}, {"a":3,"b":1,"c":1}, {"a":2,"b":1,"c":2}, {"a":2,"b":1,"c":1}, ];myArray = myArray.sort( by("a",["asc"], by("b",[], by("c",["asc"]))) ); puts(myArray); //例2 myArray = [ [1,1,1], [3,3,1], [3,4,1], [3,1,1], [2,1,2], [2,1,1] ];myArray = myArray.sort( by(0,["asc"], by(1,[], by(2,["asc"]))));puts(myArray);//例3 myArray = [-80,-13.888,-10,-9.6,-9.4,-1,2,2,3,5.823,0,7.999,20,22,55,312]; myArray = myArray.sort( by(null,["asc"]) ); iJs.put(""); iJs.put(myArray);