直接贴代码
<!DOCTYPE html>
<html>
<HEAD>
<script>
function isChCode(chCode){
var re= /^[\u4e00-\u9fa5]/;
var as = "" + chCode;
return (re.test(as));
}
//比较没有后缀的文件名
function fileNoExtCompare(a, b)
{
// 特殊字符判定
var specialChars = "!#$%^~()-+=-";
var firstCharA = a.charAt(0);
var firstCharB = b.charAt(0);
var spA = specialChars.indexOf(firstCharA);
var spB = specialChars.indexOf(firstCharB);
if(spA != spB)
{
return (spA >= 0) ? -1 : 1
}
if(spA >= 0 && spB >= 0)
{
if(firstCharA != firstCharB)
{
return firstCharB - firstCharA;
}
else
{
return fileNoExtCompare(a.substring(1), b.substring(1)) ;
}
}
//判定比较内容是不是数值
var nA = parseInt(a);
var nB = parseInt(b);
if(!isNaN(nA) && !isNaN(nB))
{
return nA - nB;
}
if(firstCharA == firstCharB)
{
return fileNoExtCompare(a.substring(1), b.substring(1)) ;
}
var isChFirstA = isChCode(firstCharA);
var isChFirstB = isChCode(firstCharB);
if(isChFirstA != isChFirstB)
{
return isChFirstA ? 1 : -1;
}
var aa = "1" + firstCharA;
var bb = "1" + firstCharB;
//return a.localeCompare(b);
return aa.localeCompare(bb,'zh-CN');
}
//比较带后缀的文件名
function fileWithExtCompare(a, b){
//debugger
var onlyNameA = a.substring(0, a.lastIndexOf("."));
var onlyNameB = b.substring(0, b.lastIndexOf("."));
var result = fileNoExtCompare(onlyNameA, onlyNameB);
if(result != 0){
return result;
}
//比较后缀
var extA = a.substring(a.lastIndexOf("."));
var extB = b.substring(b.lastIndexOf("."));
return extA.localeCompare(extB);
}
function SortFileNames(files)
{
console.log(files);
files.sort(function(a,b){return fileWithExtCompare(a, b)});
console.log(files);
}
</script>
</HEAD>
<body>
<h1>JavaScript 数组排序</h1>
<p>单击按钮可按降序对数组进行排序。</p>
<button onclick="myFunction()">试一试</button>
<p id="demo"></p>
<script>
// var files = ["2.jpg", "!!2.jpg", "身份证反.jpg", "!@2.jpg", "微信图片_20210519171233.png", "werrew微信图片_20210519171233.png", "asssd微信图片_20210519171233.png", "11.png", "businesslic_02.jpg", "微信图片_20210630144243.png", "Dingtalk_20210316113817.JPG", "营业执照2 - 副本.jpg", "Dingtalk_20210325104308.JPG", "Dingtalk_20210422202247.jpg"];
// var files = ["Dingtalk_202103251043018.JPG", "Dingtalk_20210419180528.jpg", "Dingtalk_20210422202247.jpg", "企业微信截图.jpeg", "发票.png", "定额发票《.jpg", "普通发票.jpg", "身份证反.jpg", "身份证正.jpg"]
// var files = ["a.png", "b.png", "c.jpg", "d.png", "e.png", "f.png", "g.jpg", "h.jpg", "i.jpg", "j.png", "k.jpg", "l.png", "m.png", "n.png", "o.jpg"]
var files = ["a11.jpg", "2f.png", "b2d2.JPG", "34fd.jpg", "6dfd.jpg"];
document.getElementById("demo").innerHTML = files;
function myFunction() {
SortFileNames(files);
document.getElementById("demo").innerHTML = files;
}
</script>
</body>
</html>
网友评论