- js 基礎——sort方法:
arrayObject.sort(sortby);
參數:定義排序規則(正序、倒序、按字段排序)的函數;
返回值:對數組的引用。請注意,數組在原數組上進行排序,不生成副本。
無參數時,默認為正序排序(數值數組按數值正序,字符串數組按字符正序)。
要實現不同的排序方式,只需實現sort的輸入參數函數即可。
- 正序排序:
//定義正序規則的參數函數
function NumAscSort(a,b) { return a - b; }
var arr = new Array( 3600, 5010, 10100, 801);
//進行正序排序 arr.sort(NumAscSort);
- 倒序排序:
//定義倒序規則的參數函數
function NumDescSort(a,b) { return b - a; }
var arr = new Array( 3600, 5010, 10100, 801);
//進行倒序排序 arr.sort(NumDescSort);
- 按字段排序
//定義按字段排序的規則函數
function by(name){
return function(o, p){
var a, b;
if (typeof o === "object" && typeof p === "object" && o && p) {
a = o[name];
b = p[name];
if (a === b) {
return 0;
}
if (typeof a === typeof b) {
return a < b ? -1 : 1;
}
return typeof a < typeof b ? -1 : 1;
}
else {
throw ("error");
}
}
}
//定義要排序的對象
var employees=[]
employees[0]={name:"George", age:32, retiredate:"March 12, 2014"}
employees[1]={name:"Edward", age:17, retiredate:"June 2, 2023"}
employees[2]={name:"Christine", age:58, retiredate:"December 20, 2036"}
employees[3]={name:"Sarah", age:62, retiredate:"April 30, 2020"}
//進行按“age”元素排序
employees.sort(by("age"));