中文的数组进行排序,并不是按拼音首字母进行排序,如下:
var arr = ["中","梁","丽","彬","A","B","E"];
arr.sort(); // 结果: ["A", "B", "E", "中", "丽", "彬", "梁"]
这并不是我们想要的,因为中明明是Z开头的,在这里我想它排在最后
解决办法:stringObject.localeCompare()方法,如下:
var arr = ["中","梁","丽","彬","A","B","E"];
arr.sort(function (a, b) {
return a.localeCompare(b)
}) // 结果: ["彬", "丽", "梁", "中", "A", "B", "E"]
如果你想把英文排到前面来,在排序里加多个判断即可。
js中文排序函数
//数组排序,参数:hashS是hash数组,sortKey是排序字段,asc顺序,desc倒序
function sortHashs(hashS,sortKey,sortType) {
var temp="";
var minIndex=0;
var min="";
for (var i=0;i
min=hashS[i][sortKey];
for (var j=i;j
if (hashS[j][sortKey].localeCompare(hashS[minIndex][sortKey])<0){
minIndex=j;
min=hashS[j];
}
}else if (sortType=="desc") {//倒序
if (hashS[j][sortKey].localeCompare(hashS[minIndex][sortKey])>0){
minIndex=j;
min=hashS[j];
}
}
}
if (minIndex!=i) {
temp=hashS[i];
hashS[i]=hashS[minIndex];
hashS[minIndex]=temp;
}
}
}
//数组排序,参数:strs是字符串数组,sortType是排序类型,asc顺序,desc倒序,默认为顺序
function sortStrs(strs,sortType) {
var temp="";
var minIndex=0;
var min="";
for (var i=0;i
min=strs[i];
for (var j=i;j
if (strs[j].localeCompare(strs[minIndex])<0){
minIndex=j;
min=strs[j];
}
}else if (sortType=="desc") {//倒序
if (strs[j].localeCompare(strs[minIndex])>0){
minIndex=j;
min=strs[j];
}
}
}
if (minIndex!=i) {
temp=strs[i];
strs[i]=strs[minIndex];
strs[minIndex]=temp;
}
}
}
上面的函数可以非常完美的处理中文汉字排序的一些问题。
【js中文汉字排序不正确手动修正的方法】js中文汉字排序不正确,手动修正的方法
http://m.bbyears.com/wangyezhizuo/99336.html
推荐访问: