---恢復內容開始---數組
數組排序的話最經常使用的就是array.sort()這個方法了。app
sort()裏面傳入一個方法來比較大小的值;spa
function compare(a,b) {
return a-b;
}
對象進行比較的話:按照時間排序prototype
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"));
還有一種方法是當兩個值相等時,拿另外一個參數做爲比較值code
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}]blog
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排序
---恢復內容結束---it