直接上代码:
1 var arr=[ 2 {name:"张散步",age:"23",sports:"篮球",number:"231123"}, 3 {name:"李斯的",age:"3",sports:"钢琴",number:"534563"}, 4 {name:"艾伦",age:"63",sports:"排球",number:"345455"}, 5 {name:"王武",age:"33",sports:"乒乓球",number:"867324"}, 6 {name:"乏力",age:"26",sports:"足球",number:"132457"} 7 ]; 8 9 //单一的数字排序 10 //console.log(arr.sort(sortDownAge));//正序 11 //console.log(arr.sort(sortUpAge));//反序 12 13 14 //灵活的数字多排序 15 //console.log(sortDownNumber(arr,"age"));//正序 16 //console.log(sortUpNumber(arr,"age"));//反序 17 // 18 //console.log(sortDownNumber(arr,"number"));//正序 19 //console.log(sortUpNumber(arr,"number"));//反序 20 21 22 23 24 25 //单一的纯数字排序,上方是正序,下方是反序 26 function sortDownAge(a, b) { 27 return a.age - b.age 28 } 29 30 function sortUpAge(a, b) { 31 return b.age - a.age 32 } 33 34 //纯数字灵活排序 35 /*数字正排序 36 * 37 * data:对象数组 38 * p:排序的参数 39 * 40 * */ 41 function sortDownNumber(data, p) { 42 for (i = 0; i < data.length - 1; i++) { 43 for (j = 0; j < data.length - 1 - i; j++) { 44 if (parseFloat(data[j][p]) > parseFloat(data[j + 1][p])) { 45 var temp = data[j]; 46 data[j] = data[j + 1]; 47 data[j + 1] = temp; 48 } 49 } 50 } 51 return data; 52 } 53 54 55 /*数字反排序 56 * 57 * data:对象数组 58 * p:排序的参数 59 * 60 * */ 61 function sortUpNumber(data, p) { 62 for (i = 0; i < data.length - 1; i++) { 63 for (j = 0; j < data.length - 1 - i; j++) { 64 if (parseFloat(data[j][p]) < parseFloat(data[j + 1][p])) { 65 var temp = data[j]; 66 data[j] = data[j + 1]; 67 data[j + 1] = temp; 68 } 69 } 70 } 71 return data; 72 }
分别显示的结果如下截图:
1、单一的数字排序,左侧是正序(arr.sort(sortDownAge)),右侧是反序(arr.sort(sortUpAge))
2、灵活的数字多排序,左侧是年龄正序(sortDownNumber(arr,"age")),右侧是年龄反序(sortUpNumber(arr,"age"))
3、灵活的数字多排序,左侧是number正序(sortDownNumber(arr,"number")),右侧是number反序(sortUpNumber(arr,"number"))
这是其他排序的方法,欢迎查看,欢迎给意见!