<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>用localeCompare实现中文排序</title>
<script language="javascript" type="text/javascript">
var a="aa,cc,bb,dd,啊啊,层次,宝贝,低调";
function defaultSort(){
b=a.split(",");
b.sort();
document.getElementById("out1").innerHTML="默认排序的结果:"+b;
}
function cusSort(){
c=a.split(",");
c.sort(function(e,f){
return e.localeCompare(f);
});
document.getElementById("out2").innerHTML="拼音排序的结果:"+c;
}
</script>
</head>
<body>
<a href="javascript:void(0);" οnclick="defaultSort();">默认排序</a><br>
<a href="javascript:void(0);" οnclick="cusSort();">拼音排序</a>
原字符串:
"aa,cc,bb,dd,啊啊,层次,宝贝,低调";
排序后:
<div id="out1"></div>
<div id="out2"></div>
<pre>
PS:
JavaScript中localeCompare函数方法是返回一个值,指出在当前的区域设置中两个字符串是否相同。使用方法:
stringVar.localeCompare(stringExp)
其中stringVar是必选项。一个 String 对象后文字。
stringExp是必选项。将与 stringVar 进行比较的字符串。
localeCompare 可以对 stringVar 和 stringExp 进行一个区分区域设置的字符串比较并返回 –1、0 或 +1,
这取决于系统中缺省区域设置的排序。如果 stringVar 排序在 stringExp 之前,那么 localeCompare 返回 –1;
如果 stringVar 排序在 stringExp 之后,则返回 +1。如果返回值为 0,那就说明这两个字符串是相同的。
</pre>
</body>
</html>
javascript 中文排序
最新推荐文章于 2025-02-22 15:31:57 发布