恢復內容開始 數組排序的話最常用的就是array.sort()這個方法了。 sort()裡面傳入一個方法來比較大小的值; 對象進行比較的話:按照時間排序 還有一種方法是當兩個值相等時,拿另一個參數作為比較值 然後我最近要做的是預設地址排在第一位,之後的按照時間排序 var data = [{name ...
---恢復內容開始---
數組排序的話最常用的就是array.sort()這個方法了。
sort()裡面傳入一個方法來比較大小的值;
function compare(a,b) {
return a-b;
}
對象進行比較的話:按照時間排序
function minor (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", time:1494581848, default:0} employees[1]={name:"Edward", time:2494581000, default:0} employees[2]={name:"555", default:0} employees[3]={name:"Christine", time:2491258100, default:1} employees[4]={name:"Sarah", time:123125818, default:0} employees[5]={name:"liu", default:0} employees.sort(minor("time"));
還有一種方法是當兩個值相等時,拿另一個參數作為比較值
var by = function(name,minor){ 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 typeof minor === 'function' ? minor(o,p):0; } if (typeof a === typeof b) { return a < b ? 1 : -1; } return typeof a < typeof b ? 1 : -1; } else { throw ("error"); } } } function minor (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", time:1494581848, default:0} employees[1]={name:"Edward", time:2494581000, default:0} employees[2]={name:"555", default:0} employees[3]={name:"Christine", time:2491258100, default:1} employees[4]={name:"Sarah", time:123125818, default:0} employees[5]={name:"liu", default:0} employees.sort(by("default","time"));
然後我最近要做的是預設地址排在第一位,之後的按照時間排序
function reviseSort (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 data = [{name:"George", time:1494581848, default:0},{name:"Edward", time:2494581000, default:0},{name:"Christine", time:2491258100, default:1}, {name:"Sarah", time:123125818, default:0}]
data.sort(self.reviseSort("default"));//按照預設地址排序
var data_default = [].concat(data[0]);//獲取預設地址
data.splice(0,1);//刪除預設地址
data.sort(self.reviseSort("created"));//按照時間排序
Array.prototype.push.apply(data_default, data);//把data數組插入data_default
---恢復內容結束---