JavaScript非数字(中文)排序
Posted nelsonlei
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript非数字(中文)排序相关的知识,希望对你有一定的参考价值。
直接上代码:
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 //console.log(ForwardRanking(arr,"name"));//正序 10 //console.log(ReverseRanking(arr,"name"));//反序 11 //console.log(ForwardRanking(arr,"sports"));//正序 12 //console.log(ReverseRanking(arr,"sports"));//反序 13 14 15 /* 中文正向排序 16 * 17 * data:对象数组 18 * p:排序的参数名 19 * 20 * */ 21 function ForwardRanking(data, p) { 22 for (i = 0; i < data.length - 1; i++) { 23 for (j = 0; j < data.length - 1 - i; j++) { 24 var dd = (data[j][p].localeCompare(data[j + 1][p], "zh"));//1---前者往后移,-1===位置不变 25 if (dd > 0) { 26 var temp = data[j]; 27 data[j] = data[j + 1]; 28 data[j + 1] = temp; 29 } 30 } 31 } 32 return data; 33 } 34 35 36 /*反向排序 37 * 38 * data:对象数组 39 * p:排序的参数名 40 * 41 * */ 42 function ReverseRanking(data, p) { 43 for (i = 0; i < data.length - 1; i++) { 44 for (j = 0; j < data.length - 1 - i; j++) { 45 var dd = (data[j][p].localeCompare(data[j + 1][p], "zh"));//1---前者往后移,-1===位置不变 46 if (dd < 0) { 47 var temp = data[j]; 48 data[j] = data[j + 1]; 49 data[j + 1] = temp; 50 } 51 } 52 } 53 return data; 54 }
结果如下:
1、姓名,左边是正序(ForwardRanking(arr,"name")),右边是反序(ReverseRanking(arr,"name"));
1、sports,左边是正序(ForwardRanking(arr,"sports")),右边是反序(ReverseRanking(arr,"sports"));
这是其他排序的方法,欢迎查看,欢迎给意见!
以上是关于JavaScript非数字(中文)排序的主要内容,如果未能解决你的问题,请参考以下文章