sort()方法
1 //数组排序 2 var n = [15, 99, 23, 42, 4, 8, 16]; 3 n.sort(function(a, b) { 4 return a - b 5 }); 6 console.log(n); 7 8 //字符串排序 9 var m = ['aa', 'bb', 'a', 4, 8, 15, 16, 23, 42]; 10 m.sort(function(a, b) { 11 if (a === b) { 12 return 0; 13 } 14 if (typeof a === typeof b) { 15 return a < b ? -1 : 1; 16 } 17 return typeof a < typeof b ? -1 : 1; 18 }); 19 console.log(m); 20 21 //名字比较 22 var by = function(name, minor) { 23 return function(o, p) { 24 var a, b; 25 if (o && p && typeof o === 'object' && typeof p === 'object') { 26 a = o[name]; 27 b = p[name]; 28 if (a === b) { 29 return typeof minor === 'function' ? minor(o, p) : 0; 30 } 31 if (typeof a === typeof b) { 32 return a < b ? -1 : 1; 33 } 34 return typeof a < typeof b ? -1 : 1; 35 } 36 }; 37 }; 38 var s = [{ 39 first: 'Joe', 40 last: 'Besser' 41 }, { 42 first: 'Moe', 43 last: 'Howard' 44 }, { 45 first: 'Joe', 46 last: 'DeRita' 47 }, { 48 first: 'Shemp', 49 last: 'Howard' 50 }, { 51 first: 'Larry', 52 last: 'Fine' 53 }, { 54 first: 'Curly', 55 last: 'Howard' 56 }]; 57 s.sort(by('first', by('last'))); 58 console.log(s);